OP的fgets()
用途不明确,portNum[sizeof(line)] = (char)line;
肯定是错误的。
相反:如何让下面的getchar()
代码更fgets()
样:
// 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();
}
被替换为'与fgets(行的sizeof(线),标准输入)'第二个参数是要复制到str中的最大字符数(包括终止空字符)。给它定义一个值。另外,'fgets'将继续读取,直到遇到换行符。不需要while循环。 – Ayush
'portNum [sizeof(line)] =(char)line;'你有什么想法你在做什么? –