Click here to Skip to main content
15,886,680 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include<stdio.h>
    main()
    {
    int a,b,c;
    // "a" is a two-digit integer and "b" is a five-digit integer.
    printf("Enter suitable integer values for a and b :\n");
    scanf("%2d %5d",&a,&b);
    printf("a = %2d and b = %5d\n",a,b);
    printf("Enter an integer value for c :\n");
    scanf("%d",&c);
    printf("c = %d\n",c);
    getchar();
    }


Input :
12345 32196
Output :
a = 12 and b = 345
c = 32196

The part that i understand :
Here the compiler assigns "12" to a, since field-width of "a" is 2.

The part that i don't understand :
Why does the compiler assign the remaining digits of "12345" to "b" and that of "345" to "c" ?

What I have tried:

I have tried looking for the explaination in my textbook but didn't find it.
Posted
Updated 10-Apr-16 6:27am
v4
Comments
Sergey Alexandrovich Kryukov 10-Apr-16 11:22am    
First of all, there is nothing to warn about; it all happens during runtime.
Practically, don't do such things. Instead, get a whole string and interpret it.
—SA
Shubham_Dubey 10-Apr-16 11:41am    
Yes, there is nothing to warn about.I wrote it by mistake,my apologies..
Thanks for help :)
Sergey Alexandrovich Kryukov 10-Apr-16 11:51am    
No problem. You are welcome.
—SA

1 solution

Because that is what you asked it to do!
When you specify a length in the scanf format string, that is what it looks at: scanf - C++ Reference[^]
And if you look under "whitespace":
Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
Not the last bit (I made it bold so it's clearer)
So your format string goes:
"%2d" - OK, I need two digits... 1 and 2. Excellent!
" "   - OK, I might need some whitespace - what's the next character? A digit? that'll do!
"%5d" - OK, I need five digits... 3, 4, 5...and a space. So that's the end of that number.
So when you later do the next scanf, it still has data in the buffer, and processes that.
If you want it to behave differently, you will need to read the data as a string, and break it up yourself!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900