我正在尝试将 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
文档。
关于c - 从 getchar 切换到 fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42826634/