need help with scanf("%*c") stuff.
Code:
#include <stdio.h>
int main()
{ struct student {
int snum;
char name[30];
int age;
char sex;
float score;
};
struct student info;
printf( "Input student number:" );
scanf( "%d", &info.snum );
printf( "Input student name:" );
scanf( "%*c" );
gets( info.name );
printf("Name: %s", info.name);
return 0;
}
Hi,
can anyone tell me what's the purpose of scanf( "%*c" );
because if i exclude that statement, the program compiles but does not work as i expected.
By the way, those are not my codes, my teacher gave it to me.
Thanks in advance.
Re: need help with scanf("%*c") stuff.
>my teacher gave it to me.
Then your teacher gave you crud, I'm afraid.
The use of gets() is now outdated, you should really be using fgets() or similar. And to be strict, the main should be defined like this:
>int main(void)
You should always check the return code from scanf() to ensure that it read in what you asked it to, particularly when reading numbers.
When inputing string with scanf(), it will delimit based on white space, so going by your code, if you enter the name of "Fred Bloggs", your code will only pickup Fred. The Bloggs will be left in the input buffer.
Anyway, enough ranting... in answer to your question, this:
>scanf( "%*c" );
scans for one character and doesn't assign it to a variable. This has the affect of eating one byte from the input stream, and is most likely intended to remove the newline character as was left by the first call to scanf().