我是一个新手,正在为学校编写一个 C 程序,其中输入被重定向到一个文件。我getchar()
仅用于检索信息。我正在使用 Windows Visual 2008,但我无法弄清楚为什么我的代码不会退出循环。谁能帮我吗?谢谢。
while (rec != 'EOF')
{
while (rec != '\n')
{
variable=getchar;
printf ("this is variable %c");
}
}
while (rec != EOF)
{
rec=getchar();
if((rec != '\n') && (rec != EOF)){
printf ("this is variable %c\n",rec);
}
}
答案取决于真正需要什么。如果要打印除新行之外的每个字符,则需要类似:
int c = getchar(); // Note c is defined as an int otherwise the loop condition is broken
while (c != EOF)
{
if (c != `\n`)
{
printf("c:%c\n", c);
}
c = getchar();
}
如果您只想要第一行的字符:
int c = getchar();
while (c != EOF && c != `\n`)
{
printf("c:%c\n", c);
c = getchar();
}
int c = 0;
while (c != EOF) {
c = getchar();
if (c == '\n')
break;
printf("c:%c\n", c);
}