2017-07-28 156 views
-2

我正在嘗試運行以下代碼,該代碼搜索行列表中最長的行並將其複製/保存。C語言中函數'getline'的衝突類型

int getline(char line[], int maxline); 

void copy(char to[], char from[]); 

int main() 
{ 
    int len; /* current line length */ 
    int max; /* maximum length seen so far */ 
    char line[MAXLINE]; /* current input line */ 
    char longest[MAXLINE]; /* longest line saved here */ 

    max = 0; 

    while ((len = getline(line, MAXLINE)) > 0) 
     if (len > max) { 
      max = len; 
      copy(longest, line); 
     } 

    if (max > 0) /* there was a line */ 
     printf("%s", longest); 

    return 0; 
} 


int getline(char s[],int lim) 
{ 
    int c, i; 

    for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) 
     s[i] = c; 

    if (c == '\n') { 
     s[i] = c; 
     ++i; 
    } 

    s[i] = '\0'; 

    return i; 
} 

void copy(char to[], char from[]) 
{ 
    int i; 
    i = 0; 

    while ((to[i] = from[i]) != '\0') 
     ++i; 
} 

但是,編譯器說在getline有一個錯誤,其中類型有衝突。

因此,主要是getline()通過處理其中的字符數獲取行列表中最長的行。

+2

在問之前,請至少做一個關於warnig /錯誤信息的簡單搜索!這比找到一個問題花費的時間更少。 – Olaf

+0

BTW:getline(char s [],int lim)'中的拐角錯誤。考慮'getline(s,1)',if(c =='\ n')'會發生什麼?最好使用'int c == 0;'。 – chux

+1

[Stack Overflow用戶需要多少研究工作?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) –

回答

0

由於您重新定義了原型libc函數getline()的原型,其原型在<stdio.h>中定義,所以存在衝突。

man 3 getline我們:

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

如果用int getline(char line[], int maxline)重新定義它,你與原始getline()功能衝突。

只需重命名您的函數,使其與庫不衝突。

+0

沒有跡象表明OP甚至包含標準頭文件,如果他使用POSIX系統,則更少。而且 - 請 - 至少簡單搜索一下模擬。 – Olaf

+0

你的意思是你的_answer_,而不是我想的問題? – Olaf

+0

我更新了答案,以消除不當的第三方編輯。 – Fabien