f-z-N
f-z-N

Reputation: 1827

Noticing strange behavior with strings in c

Still in learning mode and may be the following question is a really dumb but I dont have any idea why it is happening..

#include<stdio.h>
int main()
    {
      /* code to accept string and then a character from stdin */
         char str[20], inp;
         /*take string from stdin */
         printf("string:\n");
         scanf("%s",str);
         fflush(stdin);
         /*input a character */
         printf("char:\n");
         scanf("%c",&inp);/* code does not reach this point and exits */

    }

As mentioned in the comment, after I input the string , for eg. 'strng' the code just exits after printing char: but it does not wait for me input the character. As per my understanding, I have given the size of the array large enough to store the string and if the string entered is smaller than the size of the str array, the compiler will automatically add null character at the end of the string and proceed further. Am I missing something or is there a mistake in my code. Please suggest.

Thanks.

Upvotes: 1

Views: 193

Answers (3)

shubhendu mahajan
shubhendu mahajan

Reputation: 816

Try removing fflush(stdin); and put a space before %c in scanf(" %c",&inp);

Upvotes: 3

Sadique
Sadique

Reputation: 22841

Put a space before the %c in the second scanf like this:

scanf(" %c",&inp)

And as stated by others fflush is defined only for output streams.

Upvotes: 1

cnicutar
cnicutar

Reputation: 182734

First of all fflush(stdin) is wrong. Many people recommend it but it is plain and simple undefined.

The problem is caused by scanf leaving \n in the input buffer because "%s" doesn't read whitespace characters. When scanf("%c"..) is reached, it is immediately "satisfied" and fills inp with \n and calls it a day.

The problem is common enough, see these C FAQs:

One (possibly dangerous) solution is to discard \n input:

while((c = getchar()) != '\n' && c != EOF)
    ;

Another solution might be to use fgets and parse that, or possibly read one character at a time with getc, or maybe tweak the second scamf to discard whitespace characters.

Upvotes: 2

Related Questions