简体   繁体   中英

Unable to read in file — C

I'm sorry, I've done something similar to this before and I'm sure I'm over complicating this, but could someone help me understand whats wrong? I've only known java previously, but I'm getting familiar with C.

I have tried 3 different ways from searches online, the one not commented out is the one I'd prefer to use. It's printing out the right amount of numbers in data.txt but it only prints out the number 1. I thought the c = scanf inside the while would give me a different result each time.

I also tried just reading in the numbers as a char since I'm not doing any math, but I got a bunch of funky symbols.

input:

./a.out < data.txt

data.txt contents: 0 2 2 0 6 1 0 7 4 1 7 5 0 8 2 0 8 9 1 15 13

c file content: #include #include "queue.h"

int main(void)
{
    /*
    char c = scanf("%c", &c);
    while (c!= EOF)
    {
        printf("%c", c);
        c = scanf("%c", &c);
    }//while
    */



    int c = scanf("%d", &c);
    while (c!= EOF)
    {
        printf("%d", c);
        c = scanf("%d", &c);
    }//while
    printf("\n");



    /*
        char c;
    //char **argv
    FILE *infile;
    infile=fopen(argv,"r");
    while (!feof(infile))
    {
        fscanf(infile, "%c", &c);
        printf("%c", c);
    } // while
    fclose(infile);
    */
return 0;

}

You should use a different variable for checking the result of scanf than for storing the value read. As you have it now, you immediately overwrite the read value with the scanf result.

Also, it is better to check for success than to check for EOF, as if there is text entered you will go into an infinite loop.

int x = scanf("%d", &c);
while ( x == 1 )
{
    printf("%d", c);
    x = scanf("%d", &c);
}

Obviously this can be condensed:

while ( 1 == scanf("%d", &c) )
    printf("%d", c);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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