Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"printf" and "scanf", something wrong with stream

Tags:

c

So here is my code.

int main(int argc, char* argv[])
{
    char c;
    size_t place;
    while (1) {
        scanf("%c %u", &c, &place);
        printf("%c\n", c);
    }
    return 0;
}

When I compiled and ran program I expected to see terminal like this:

a 1
a
b 2
b
c 3
c

But I saw this:(some extra '\n')

a 1
a
b 2


b
c 3


c

Please help me find what I did wrong.

like image 438
pointer Avatar asked Aug 01 '26 05:08

pointer


2 Answers

You may try like this:

scanf(" %c %u", &c, &place);
      ^^--Add space here

instead of

scanf("%c %u", &c, &place);
like image 145
Rahul Tripathi Avatar answered Aug 02 '26 17:08

Rahul Tripathi


printf("char is %c\n", c); Adding some string before printing the received character will helps you to understand more clearly why its behaving like this. After your input some blank spaces or new line is entered, that is used in the next scanf. You can even print the ascii value of the charater like printf("char is %d, %c", c, c); and serach the ASCII value in the ASCII table, to understand exactly which value (blanks or new line or tab) scanf has received mistakenly.

Keeping blankspace as first character in format string of scanf will helps to skip all leading blanks(including tabs and newline). Like scanf(" %c %u", &c, &place);

like image 21
finalsemester.co.in Avatar answered Aug 02 '26 18:08

finalsemester.co.in