开发者

C getchar error

开发者 https://www.devze.com 2023-02-22 05:05 出处:网络
I wrote the most innocuous C program but I can\'t get the expected result. I hope you can tell where my error is.

I wrote the most innocuous C program but I can't get the expected result. I hope you can tell where my error is.

This is the code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    int c, var4;
    double var1,var2,var3;

    while ((c = getchar()) != EOF)开发者_StackOverflow社区 {

        while (c != ':') {
            putchar(c);
            c = getchar();
        }
        //scanf("%d/%d/%d",&mm,&dd,&yy);
        //scanf("%lf%lf%lf%d",&var1,&var2,&var3,&var4);  
    }
    return 0;
}

and I'm using this file for input(command line redirection)

Name1 - Code1:

04/03/2011 4.5 5.6 9.8 145

04/03/2011 6.5 4.6 9.9 185

Name2 - Code2:

05/03/2011 4.5 5.6 9.8 135

05/03/2011 6.5 4.6 9.9 165

The error appears during while loop (I tried printf instead of putchar and it prints -1 endlessly and seems to never reach EOF)

I thinks that's all, I thank your help in advance.


You are getting one character, then going into the inner loop — which checks for ':', but not for EOF. So, unless the file ends with : (so that it will be seen by the outer loop), the inner loop will spin forever when it hits EOF.


The inner loop doesn't stop at EOF.

You're getting an error from getchar (EOF == -1) because thee file is finished. That's what it's printing endlessly.


You are not checking for EOF inside your inner getchar loop, therefore allowing it to continuously read EOF (-1) and printing that out.

I don't know what your expected result is so I cannot help you there.

0

精彩评论

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