physicsbot123
physicsbot123

Reputation: 71

scanf taking multiple char inputs

int main() {
 char a1, a2;
 printf("input values here: ");
 scanf(" %c%c ", &a1, &a2);
 printf("%c%c",a1,a2);
}

I am trying to understand how scanf works when it is given two character inputs at once. After running this in terminal with 14, for example, I had expected to assign 1 to a1 and 4 to a2 but it did not work. Given that I must separate a terminal input of "a4" for example, into two seperate chars, how would I go about doing so? Any insights would be greatly appreciated.

./main
input values here: 14

Upvotes: 1

Views: 875

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409432

With scanf when it sees a space in the format string, it will read (and discard/ignore) any number of white-space characters. And for that to work, the scanf function needs to find the end of the non white-space characters.

The problem with a trailing space, like you have in your scanf format string, is that to find the end of the trailing white-space sequence you must enter at least one extra non white-space character.

The simple solution to your problem (as I guess it is) is to drop the trailing space in the scanf format string.

Upvotes: 4

Related Questions