簡體   English   中英

while循環中的getchar()問題

[英]getchar() in a while loop Question

我是一個新手,正在為學校編寫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 = 0;
while (c != EOF) {
    c = getchar();

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

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

答案取決於實際需要什么。 如果要打印除換行外的所有字符,則需要類似以下內容的內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM