I have some code that reads a string of the form name 1
in a while
loop, and then I have to extract the integer value to print yes or no. But when I tried to do it with sscanf
, it gives the destination integer the value only after the loop finishes.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char a[20];
int p = 0;
while (scanf("%s", a)) {
sscanf(a, "%d", &p);
if (p != 0) {
printf("yes");
} else {
printf("no");
}
}
return 0;
}
even though the string I introduce has the integer greater than 1
, the program always prints no
.
I tried to evaluate the output with printfs and I saw that when I execute it gives this output:
printf("%d", p);
For the input:
name 1
it prints:
0no1yes
As I said, it first gets the integer as 0
and after entering the if
it becomes 1
.
In this call of scanf
while(scanf("%s",a)) {
the conversion specifier s
allows to read only a text that is separated by spaces. That is if you will enter
name 1
then the first call of scanf
will read only the text "name"
and in the next iteration of the loop the call of scanf
will read the text "1"
that indeed can be converted to an integer.
You need to use another conversion specifier in the call of scanf
.
And the condition in the while loop
while(scanf("%s",a)) {
In fact you have an infinite loop.
Also your program contains redundant include directive.
The program can look the following way.
#include <stdio.h>
int main( void )
{
char a[20];
while ( scanf(" %19[^\n]",a ) == 1 )
{
int p = 0;
sscanf( a,"%*s%d", &p );
if ( p )
{
puts( "yes" );
}
else
{
puts( "no" );
}
}
return 0;
}