c – How to read from input until newline is found using scanf()?

c – How to read from input until newline is found using scanf()?

scanf (and cousins) have one slightly strange characteristic: white space in (most placed in) the format string matches an arbitrary amount of white space in the input. As it happens, at least in the default C locale, a new-line is classified as white space.

This means the trailing n is trying to match not only a new-line, but any succeeding white-space as well. It wont be considered matched until you signal the end of the input, or else enter some non-white space character.

One way to deal with that is something like this:

scanf(%2000s %2000[^n]%c, a, b, c);

if (c==n)
    // we read the whole line
else
    // the rest of the line was more than 2000 characters long. `c` contains a 
    // character from the input, and theres potentially more after that as well.

Depending on the situation, you might also want to check the return value from scanf, which tells you the number of conversions that were successful. In this case, youd be looking for 3 to indicate that all the conversions were successful.

scanf(%2000s %2000[^n], a, b);

c – How to read from input until newline is found using scanf()?

use getchar and a while that look like this

while(x = getchar())
{   
    if(x == n||x == )
       do what you need when space or return is detected
    else
        mystring.append(x)
}

Sorry if I wrote a pseudo-code but I dont work with C language from a while.

Leave a Reply

Your email address will not be published.