Reputation:
I want to read some user input and do something with each input. I do that using this code:
char c;
while(1){
printf("input");
c = scanf ( "%s", &c ) ;
}
This works fine . But I need it to accept even an empty input. But it just continues to next line and expects an not-empty input. How could I do that?
Current situation:
input:asdf
input:b
input:c
input:d
input:e
input:
fjhkjh
Expected :
input:asdf
input:b
input:c
input:d
input:e
input:blabla
input:f
input:
input:
Just how the cmd console works like... UPDATE: I don't read only one single charcater, that was an example
Upvotes: 0
Views: 1481
Reputation: 853
First you must have to use getchar(); or %c in scanf for a single character then you can use a if for test which is the input character
char c;
while(1)
{
c=getchar();
if(c==' ')
break();
}
This is only for single character input.
Upvotes: 0
Reputation: 134316
First of all, in your code,
scanf ( "%s", &c ) ;
invokes undefined behavior.
, as you cannot fit an incoming string inside a char
.
That said, %s
skips the leading white-spaces and reads the non-white-spaces up to the immediate white-space and ignores the last white-space, so you cannot read only white-spaces using %s
.
Quoting C11
, chapter §7.21.6.2, fscanf()
, (emphasis mine)
s
Matches a sequence of non-white-space characters.If no
l
length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically.
So, we can clearly see, c
is no sufficient to hold even a single char
input, either, it will be out of bound access to store the terminating null.
You seem to be in need to getchar()
or similar.
Upvotes: 0
Reputation: 1398
First of all You shouldn't use %s to store input in a single character as %s is for string of characters terminated by null character(\0). Don't use & with %s in scanf(). To store a single character make use of:
scanf("%c",&c);
or
c = getchar();
Upvotes: 1
Reputation: 417
It doesn't internally work like that, you have declared it as single char but you have used %s which is a char array. the char you get as input are stored as null values.. every character you gave a b c d e are taken as null..
if you have doubt, add a printf("%s",c);
below the scanf();
Upvotes: 0