int m[3];
scanf( "%1d%1d%1d", &m[0], &m[1], &m[2] );
I would expect input "123" (without the quotes) to store values 1, 2 and 3 in the array.
What am I doint wrong?
int m[3];
scanf( "%1d%1d%1d", &m[0], &m[1], &m[2] );
I would expect input "123" (without the quotes) to store values 1, 2 and 3 in the array.
What am I doint wrong?
I would expect it to do the same. Can you post a complete program which demonstrates the error?I would expect input "123" (without the quotes) to store values 1, 2 and 3 in the array.
Okay, problem seems to be left over from previous scanf:
int year, data[3];
printf( "Year = " );
scanf( "%d", &year );
printf( "data = " );
scanf( "%1d%1d%1d", &data[0], &data[1], &data[2] );
Year reads into storage ok. Second scanf() doesn't hang up, but doesn't place any values in data[], either. Somehow the CR/LF needs to be handled when reading the year, but I can't figure out how to do it.
Paul
> What am I doint wrong?
a) not reading the manual
b) assuming that printf and scanf are perfectly symmetrical in their format strings - they are not.
scanf does NOT have field widths on input, so your attempt to read only 1 digit is broke.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Thanks, folks, for trying to help. Here is the solution:
int year, data[3];
char dum;
printf( "Year = " );
scanf( "%d%c", &year, dum );
printf( "data = " );
scanf( "%1d%1d%1d%c", &data[0], &data[1], &data[2], dum );
Apparently the %c takes care of the CR in the first scanf(), leaving the buffer ready for the next one.
What the manual says about this (Harbison and Steele, pg 326) is "Trailing whitespace characters (such as the newline that terminates a line of input) will remain unread unless explicitly matched in the control string. However, doing this may be tricky ..." I had read that, but wasn't bright enough to understand what it meant until I had done a lot of experimentation. Finally got it right.
Again, thanks to you all,
Paul
You need to use &dum, if dum is a char variable.
That will, I suppose, work, but it is overkill since what you had originally worked too.
Don't forget [code]code tags[/code] in the future!
<< !! Posting Code? Read this First !! >>