c - 从 getchar 切换到 fgets

标签 c while-loop fgets getchar

我正在尝试将 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 的使用是错误的。

fgets Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

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

此外,参数使用错误。

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

str => Pointer to an array of chars where the string read is copied.

num => Maximum number of characters to be copied into str (including the terminating null-character).

stream => Pointer to a FILE object that identifies an input stream. stdin can be used as argument to read from the standard input.

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

fgets man page

关于c - 从 getchar 切换到 fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42826634/

相关文章:

这段代码可以与 fgets 一起使用吗?

c - 如何突破fgets?

C 插入排序陷入 while 循环

c - 使用 AES 新指令集解密时出现错误结果

c - 如何将 char(ASCII 字符)转换为保存在 C 字符串变量中的科学计数法

c - 这是一个 C 程序,用于计算从 0 到 n 的 k 的总和 : nCk . 我遇到了段错误

java - 使用 while 循环从输入获取特定系列的数字时遇到问题

java - 使用循环计数的作业分配(Java)

c - 使用 fgets 和 put 读取和打印文件不起作用

c - 编写一个程序来检查给定的输入字符串是否有平衡括号