#include <stdio.h>
#include <string.h>
#include<stdio.h>
int main()
{
int ch;
char str;
scanf("%d", &ch);
scanf("%c", &str);
printf("x = %d, str = %c", ch, str);
return 0;
}
Input: 10(enter)
Output: x = 10, str =
here in this code scanf("%d", &ch); reads an integer and leaves a newline character in buffer. So scanf("%c", &str); only reads a newline character. Which i understood.
But when i run this code:
#include <stdio.h>
#include <string.h>
#include<stdio.h>
int main()
{
int ch;
char str[54];
scanf("%d", &ch);
scanf("%s",str);
printf("x = %d, str = %s", ch, str);
return 0;
}
Input: 10(enter) test
Output: x = 10, str = test
here it seems like scanf("%s",str); ignores the newline character from the buffer and reads test from console.
Why this is happening?
CodePudding user response:
Why this is happening?
That is what %s
is specified to do in scanf
. In the 2018 C standard, clause 7.21.6.2, paragraphs 7 and 8 say:
… A conversion specification is executed in the following steps:
Input white-space characters (as specified by the
isspace
function) are skipped, unless the specification includes a[
,c
, orn
specifier.
So, all the conversions except %[
, %c
, and %n
skip initial white-space characters, which includes new-line characters.
Generally, scanf
is not intended to be a full-power parser that facilitates examining every character in the input stream. It is intended to be a convenience mechanism, for reading simple data formats without a lot of rigid constraints. Skipping white-space is part of that.
CodePudding user response:
"test" it's not ignored, the problem is that you're requesting an int (read only numbers), and then a string (read until \n or space, without reading those).
int ch;
char str[100];
scanf("%d", &ch); // this will read "10" and leave "\ntest\n" on the buffer
scanf("%s", str); // this will read "", so it will ask to the user an input. ("\ntest\n" is still on the buffer)
What you want is this:
int ch;
char str[100];
scanf("%d", &ch); // this will read "10" and leave "\ntest\n" on the buffer
scanf("%c", &str[0]); // this will read "\n" and leave "test\n" on the buffer
scanf("%s", str); // this will read "test" and leave "\n" on the buffer