【问题标题】:switching from getchar to fgets从 getchar 切换到 fgets
【发布时间】:2017-03-16 06:19:46
【问题描述】:

我正在尝试将我对 getchar 的使用切换到 fgets,但是在使用 getchar 时,整个代码都不起作用。

//fgets(line, sizeof(line), stdin);

  while(fgets(line, sizeof(line), stdin))
  {
   portNum[sizeof(line)] = (char)line;
  }

while((c = getchar()) != '\n')
{
    portNum[num++] = c;
}
portNum[num] = '\0';

我怎样才能使这两个功能相等才能正常工作?

【问题讨论】:

  • 对于fgets(line, sizeof(line), stdin),第二个参数是Maximum number of characters to be copied into str (including the terminating null-character).。给它一个定义的值。此外,fgets 将继续阅读,直到遇到换行符。不需要while循环。
  • portNum[sizeof(line)] = (char)line;你知道你在做什么吗?

标签: c while-loop fgets getchar


【解决方案1】:

您对fgets 的使用是错误的。

fgets 从流中读取字符并将它们作为 C 字符串存储到 str 中,直到读取 (num-1) 个字符或到达换行符或文件结尾,以先发生者为准。

在您的情况下,fgets 将读取所有字符,直到遇到换行符。

另外,参数使用错误。

char * fgets(char * str, int num, FILE * stream);

str => 指向复制读取字符串的字符数组的指针。

num => 复制到 str 的最大字符数(包括 终止空字符)。

stream => 指向标识输入流的 FILE 对象的指针。 stdin 可用作从标准输入读取的参数。

有关详细信息,请参阅fgets 文档。

fgets man page

【讨论】:

    【解决方案2】:

    OP 的fgets() 用法不清楚,portNum[sizeof(line)] = (char)line; 肯定有误。

    改为:如何使下面的getchar() 代码更像fgets()-like:

    // assumed missing code
    #define N 100
    int c;
    char portNum[N];
    size_t num = 0;
    
    // size and EOF detection added (which should have been there)
    while(num + 1 < sizeof portnum && (c = getchar()) != '\n' && c != EOF) {  
        portNum[num++] = c;
    }
    portNum[num] = '\0';
    
    // assumed missing code
    if (c == EOF && num == 0) Handle_EndOfFile_or_InputError();
    else ...
    

    这可以替换为fgets()代码

    #define N 100
    char portNum[N+1]; // 1 larger for the \n
    
    if (fgets(portNum, sizeof portNum, stdin)) {
      // lop off potential trailing \n
      portNum[strcspn(portNum, "\n")] = '\0';
      ...
    } else {
      Handle_EndOfFile_or_InputError();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 2018-11-08
      • 2010-10-10
      • 2017-02-06
      • 2018-11-04
      相关资源
      最近更新 更多