我正在使用 Xcode 8 学习 C,编译器在执行 while 或 for 循环后不会运行任何代码。这是一个错误吗?我该如何修复它?
在下面提供的示例中printf("code executed after while-loop");
从不执行
#include <stdio.h>
int getTheLine(char string[]);
int getTheLine(char string[]) {
char character;
int index;
index = 0;
while ((character = getchar()) >= EOF) {
string[index] = character;
++index;
}
printf("code executed after while-loop");
return index;
}
int main(int argc, const char * argv[]) {
char string[100];
int length = getTheLine(string);
printf("length %d\n", length);
return 0;
}
最佳答案
getchar
返回 int
而不是 char
,与 EOF
的比较应使用 !=
运算符而不是 >=
运算符。
...
int character; // int instead of char
int index;
index = 0;
while ((character = getchar()) != EOF) { // != instead of >=
...
关于c - C 语言中 while 或 for 循环后不执行任何代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44539313/