开发者

getchar() in a while loop Question

I am a newbee writing a C program for school where the input is redirected to a file. I am to use getchar() only to retrieve the information. I am using Windows Visual 2008 and I cannot figure out why my code will not exit the loop. Can anyone help 开发者_Python百科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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜