Mathew
Mathew

Reputation: 1430

reading an entire line including spaces using c

I am trying to read an entire line from the user including white space, however my code right now does the scanf correctly only on the first iteration of the for loop. After that it simply prints x 9 times rather than asking the user again for more input. It is as if the scanf doesn't get called on the subsequent iterations Why is this? How can I fix this? My code is below. Thanks

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

int main(){
    char x[1024];
    for (int n=0; n<10; n++){
        scanf("%[^\n]s",x);
        printf("x = %s\n",x);
    }

Upvotes: 1

Views: 1082

Answers (2)

Stephan Lechner
Stephan Lechner

Reputation: 35154

scanf("%[^\n]s",x) reads in everything except a \n. This means that after the first read, it will leave the \n in the buffer, such that every consecutive read will not read in anything (that's why x remains as is).

For reading in lines (i.e. having a correct treatment of the \n), fgets is usually much better suited. And when you want to get rid of the \n-character (which will be part of the string read in by fgets), you can use the strcspn-function:

int main(){
    char x[1024];
    for (int n=0; n<10; n++){
        if (!fgets(x,1024,stdin)) {
           break;
        }
        x[strcspn(x,"\n")]='\0';
        printf("x = %s\n",x);
    }
}

Upvotes: 5

Schwern
Schwern

Reputation: 164809

The scanf family has myriad problems including leaving items in the buffer which it will then continue to re-read. That's what's happening to you. If you don't need to use it, don't use it.

Use fgets to read whole lines. Then if you want to parse the line further use sscanf.

char line[BUFSIZ];
while( fgets(line, sizeof(line), stdin) != NULL ) {
    ...
}

Upvotes: 7

Related Questions