user15765109
user15765109

Reputation: 41

Please help! I am trying to get input from a file with spaces I keep getting infinite loop. C programming

I am trying to read every word in a file and print it to the screen. I want The program to accept spaces but it gives me an infinite loop when I use this %[^\n]

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


int main()
{
    FILE *DoThis;
    DoThis = fopen("Encrypppc.txt", "r");
    char word2[48];
    while(!feof(DoThis)){

        fscanf(DoThis,"%47[^\n]s",word2);
        printf("%s\n", word2);
        
    }
return 0;
}

Try to create a file and input spaces in the first sentence. It gives an infinite loop in the first sentence when there's space so it never reaches eof.

Upvotes: 1

Views: 45

Answers (2)

Mike Housky
Mike Housky

Reputation: 4069

You have an 's' that doesn't belong in the format string. Try this:

fscanf("%47[^\n]%*c", word2);

That will get you past the failure to read the end of file and on to the next problem. I added the %*c format to read and ignore the next character (either a \n newline or the end of file). That does (more precisely) what you accomplish with the leading space (which discards all spaces and tabs up to the next nonblank character.)

That "next problem" is the one mentioned in comment that feof() only goes true after an attempt to read past the end of file. You'll see your last line twice. The leading space in the format might work for you, but a better solution is to use the return value from fscanf() to tell you if the input read anything:

while (1)
{
    int n = fscanf("%47[\n]%*c", word2);
    if (n != 1) break;
    ...do something with word2
}

The ?scanf functions return the number of fields successfully converted and stored. There's only one such field in your format, so the return will be 1 whenever the input succeeded, or something else if it didn't. (Both 0 and EOF are possible returns, depending on the state of the file beforehand.)

Upvotes: 1

user15765109
user15765109

Reputation: 41

I found the answer I supposed to add a space in the fscanf function. this is what gives me the infinite loop

fscanf(DoThis,"%47[^\n]s",word2);

after I add a space before the sign % there's no infinite loop and the loop stops at EOF

fscanf(DoThis," %47[^\n]s",word2);

notice the change

Upvotes: 1

Related Questions