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?

1
  • 1
    Do you try to add \n in your scanf ? Commented Jan 5, 2014 at 10:59

3 Answers 3

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 */
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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').

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.