1

I have to read a series of input from a file using scanf. But there are different outcomes in 2 situations. Code1- Reading an integer and a char array.

char plaintext[20];
int started = 0;
int x;


while (scanf("%i,%19[^\n]",&x,plaintext) == 2)
{
    if (started == 1)
        printf(",\n");
    else 
            started = 1;
    printf("i read a line from a file");
}
printf("\n");

This works perfectly fine. The scanf reads every line in the file and the printf() outputs the required line for each line input.

Code2-Reading only a char array

char plaintext[20];
int started = 0;

while (scanf("%19[^\n]",plaintext) == 1)
{
    if (started == 1)
        printf(",\n");
    else 
            started = 1;
    printf("i read a line from a file");
}
printf("\n");

Here, the scanf reads only the first line and prints "i read a line from a file" only once.Why??

One solution is using %*c in scanf in Code 2. But why Code 1 works fine, but not Code 2.

1
  • 2
    A newlines left in the previous input will be rejected with the next entry. "%19[^\n]" --> "%19[^\n]%*c" Commented Apr 30, 2017 at 6:28

1 Answer 1

2

You need to change

scanf("%19[^\n]",plaintext)

so that it reads the new line character that is in the buffer after reading the first line.

Try

scanf("%19[^\n] ",plaintext)

The space reads the new line character at the end of the line

Sign up to request clarification or add additional context in comments.

4 Comments

Sir could we use '\r' instead of space there?
scanf - From this page A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input. - So yes
But why such new line character reading is not required in Code1 but is necessary in Code2.
The %i will consume the white space in code1. Code 2 %19[^\n] does not consume the new line character

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.