user12316583
user12316583

Reputation:

Scanf reads wrong value

I’m new to C programming language, I have wrote a simple code that reads two “char” values and prints them on the screen but the second one got empty value for a strange reason. What’s going wrong with my code?

Char c;
Scanf(“%c”,&c);
Printf(“Value:%c”,c);
Scanf(“%c”,&c);
Printf(“Value:%c”,c);

Output: Value:g Value:

Upvotes: 0

Views: 2125

Answers (2)

Steve Summit
Steve Summit

Reputation: 47933

If your goal was to read two "interesting" characters, and if you don't think that whitespace characters like space and newline are "interesting", you've been tripped up by number six out of the seventeen things about scanf that are designed to trip up the unwary: %c does read whitespace characters.

If you want scanf to skip over whitespace characters, so that %c will read the next, non-whitespace or "interesting" character, simply include a space character in the format string before the %c:

char c;
scanf(" %c", &c);
printf("Value: %c\n",c);
scanf(" %c", &c);
printf("Value: %c\n",c);

In a scanf format string, the presence of a whitespace character indicates that you want scanf to skip over all whitespace at that point in the input.

Normally you don't have to worry about skipping whitespace with scanf, because most of the other format specifiers -- %d, %f, %s, etc. -- automatically skip over any whitespace, if necessary, before they start parsing their input. But %c is special: someone thought you might want to use it to read whitespace characters, so it doesn't skip them, so if you don't want to read them, you have to skip them yourself, with that space character in the format string first.

Upvotes: 1

William Pursell
William Pursell

Reputation: 212238

(This is a comment, but comments are hard to format)

There's nothing wrong with your code (other than the failure to check the value returned by scanf and deal with errors or incorrect input). Consider:

#include <stdio.h>
int
main(void)
{
        char c;
        scanf("%c",&c);
        printf("Value:%c",c);
        scanf("%c",&c);
        printf("Value:%c",c);
        return 0;
}
$ gcc a.c
$ printf 'abc' | ./a.out
Value:aValue:b

Perhaps what's "wrong" is that you have newlines in your input. (eg, you are entering data interactively and forgetting that when you hit "return" a newline is inserted into the input stream.)

Upvotes: 2

Related Questions