What is wrong with the given C code? Why I am unable to get the desired output?
When I Input "123 + hello = 234"
I expect the output as "123 hello 234"
.
But the Output is "123 + hello"
?
Please someone explain the logic with whats wrong and the correct way to get the input.
Also please suggest references for further reading of similar topic.
#include<stdio.h>
int main()
{
char str1[11],str2[11],str3[11],ch1,ch2;
scanf("%s",str1);
scanf("%c",&ch1);
scanf("%s",str2);
scanf("%c",&ch2);
scanf("%s",str3);
printf("%s %s %s\n",str1,str2,str3);
return 0;
}
as per your input
123 + hello = 234
The whitespace matters. The immediate whitespace after 123
goes to ch1
and +
to str2
.
Without having an explicit whitespace in %c
, it will consider the whitespace in input as valid input for scan.
Try something like
scanf(" %c",&ch1);
^
|
Which tells scanf()
to discard all leading whitespace characters and read the next first non-whitespace character, in your case +
.
Sidenote: Always check the success ogf scanf()
by checking the return value. Good Practice