0

I want to input data by format "%d:%c"

I have this:

#include <stdio.h>

int main() {
    int number;
    char letter;
    int i;

    for(i = 0; i < 3; i ++) {
        scanf("%c:%d", &letter, &number);
        printf("%c:%d\n", letter, number);
    }
}

I expect this:

Input: "a:1"
Output: "a:1"
Input: "b:2"
Output: "b:2"
Input: "c:3"
Output: "c:3"

But my program doing something like this:

a:1
a:1
b:2

:1
b:2

--------------------------------
Process exited with return value 0
Press any key to continue . . .

What is the problem here?

3 Answers3

6

It's because when you read the input with scanf, the Enter character is still left in the buffer, so your next call to scanf will read it as the character.

This is easily solvable by telling scanf to skip whitespace, by adding a single space in the format code, like

scanf(" %c:%d", &letter, &number);
/*     ^                */
/*     |                */
/* Notice leading space */
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

this link might be helpful. using of %c after %d in scanf() function leads you in such difficulty.

Explaining in short, the '\n' you input after giving the number input of first test case will be taken as character input of second test case.

to avoid that you can edit your scanf statements as scanf(" %c:%d",...); . A leading space before %c avoids taking all those '\n' inputs as characters.

Community
  • 1
  • 1
vinayawsm
  • 845
  • 9
  • 28
0

OP says "... input data by format "%d:%c", yet code uses "%c:%d" and data input implies "char" then "number".

Suggest:

1) Determine the order desired.

2) Use a space before "%c" as in " %c" to consume leading whitespace like the previous line's Enter (or '\n').

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256