Reputation: 35
I am trying a c program with following input.
6
7.0
How are you
I am able to read and print the integer and double datatype variable but string variable is not accepting any input from user and printing the integer variable value by itself
Code for int
:
int j;
double e;
char str[100];
printf("enter the integer variable :");
scanf("%d", &j);
printf("enter the double variable :");
scanf("%lf", &e);
printf("enter the string :");
scanf("%[^\n]s",str);
printf("integer variable is %d\n",j);
printf("float variable is %0.1f\n",e);
printf("string variable is %s\n", str);
Output:
enter the integer :3
enter the double :4.0
enter the string :integer variable is 3 -> (automatically accepting printf of integer case and exiting the code)
float variable is 4.0
string variable is ??LX?
But If I am reading string value first (before reading integer and double) then code is working fine.
Code for string
:
printf("enter the string :");
scanf("%[^\n]s",str);
printf("enter the integer variable :");
scanf("%d", &j);
printf("enter the double variable :");
scanf("%lf", &e);
printf("integer variable id %d\n",j);
printf("float variable is %0.1f\n",e);
printf("string variable is %s\n", str);
Output:
enter the string :how are you
enter the integer :6
enter the double :7.0
integer variable is 3
float variable is 4.0
string variable is how are you
Upvotes: 2
Views: 360
Reputation: 144685
Add a space before the conversion format in scanf()
:
scanf(" %99[^\n]", str); // skip whitespace and read up to 99 characters on a line
This will instruct scanf()
to skip the pending newline sitting in the stdin
buffer, as well as any leading spaces in the next line. As a matter of fact, it will keep reading lines until the user types a non empty one or the end of file is reached. You should test the return value of scanf()
to verify if scanf()
succeeded.
Furthermore, you must tell scanf()
the maximum number of characters to store into str
otherwise a sufficiently long line of input will cause a buffer overflow with dire consequences, as this may constitute an exploitable flaw.
Note also that the syntax for parsing a scanset is %99[^\n]
: no trailing s
is required.
Upvotes: 4