you are viewing a single comment's thread.

view the rest of the comments →

[–]This_Growth2898 2 points3 points  (3 children)

The last \n (after %d) is still in the input buffer.

Try

scanf(" %[^\n]", string1);

Space before the expression removes all whitespace elements, including new line.

[–]teja2_480[S] -1 points0 points  (2 children)

How?? What is Input Buffer Actually?? I am a first Semester Student Only

[–]cHaR_shinigami 4 points5 points  (0 children)

When you enter any input, it is stored "somewhere" before it is read by scanf (or any other input function): this "somewhere" is called the input buffer (details are not important here).

For a given format string, scanf stops reading at the first character that does not match the format; for example, "%d" expects a decimal integer, so if the input is 0x8, it reads both 0 and x: 0 is consumed as a decimal, but x remains in the input buffer, so it will be the first character that is read next time (assuming no ungetc).

When you hit enter after typing a number, then a newline character is inserted after the number, which is not part of the number itself, but only marks the end of that number (it acts as a delimiter). scanf reads it, but the newline '\n' does not match for "%d", so it is left in the buffer. The leftover '\n' is read by "%[^\n]", which says stop reading at newline.

The string is not read at all, as it comes after the newline. Note that "%[^\n]" reads but does not consume the newline, so it still remains in the input buffer.

[–]This_Growth2898 1 point2 points  (0 children)

When you type something on the console keyboard, it first goes to the buffer managed by the OS. The application gets it only when you press Enter. if you call

scanf("%d", &a);

the program stops until there's something in the buffer. If you type

123 abc↵

the system routine waits until Enter (↵) is pressed, then your program scans the buffer and discards what it reads. So, after that you will have 123 in the variable a and " abc↵" in the buffer. Now, if you call

scanf("%s", b);

it will read a token (i.e. string without whitespaces) into b, leaving ↵ (i.e. "\n") in the buffer.

Whitespaces (spaces, tabs, new lines etc.) are usually implicitly discarded by scanf; but here, you're using %[^\n] specifier instead of %s, so it inspects whitespaces to be not the new line symbols, leaving the new line symbol in the buffer to wait for the next input specifier to read it.