简体   繁体   English

while循环中的getchar()问题

[英]getchar() in a while loop Question

I am a newbee writing a C program for school where the input is redirected to a file. 我是一个新手,正在为学校编写C程序,将输入重定向到文件。 I am to use getchar() only to retrieve the information. 我仅使用getchar()来检索信息。 I am using Windows Visual 2008 and I cannot figure out why my code will not exit the loop. 我正在使用Windows Visual 2008,但无法弄清楚为什么我的代码不会退出循环。 Can anyone help me out? 谁能帮我吗? Thanks. 谢谢。

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 = 0;
while (c != EOF) {
    c = getchar();

    if (c == '\n')
        break;

    printf("c:%c\n", c);
}

The answer depends on what is really needed. 答案取决于实际需要什么。 If you want to print every character except the new lines, you want something like: 如果要打印除换行外的所有字符,则需要类似以下内容的内容:

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();
}

If you just want the characters on the first line: 如果只需要第一行中的字符:

int c = getchar();
while (c != EOF && c != `\n`)
{
    printf("c:%c\n", c);
    c = getchar();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM