#include <stdio.h>
int main(int argc, char **argv)
{
int valA;
char valB;
scanf ("%d", &valA);
printf ("valA=%d\n", valA);
scanf ("%c", &valB);
printf ("valB=%c\n", valB);
return 0;
}
Result:
3
valA=3
valB=
Expect result:
3
valA=3
4
valB=4
Reason: scanf() doesn't handle new line character, "\n".
Solution1: Discard the last character "\n" by "%*c".
#include <stdio.h>
int main(int argc, char **argv)
{
int valA;
char valB;
scanf ("%d%*c", &valA);
printf ("valA=%d\n", valA);
scanf ("%c%*c", &valB);
printf ("valB=%c\n", valB);
return 0;
}
Solution2: Add a space character to second scanf().
#include <stdio.h>
int main(int argc, char **argv)
{
int valA;
char valB;
scanf ("%d", &valA);
printf ("valA=%d\n", valA);
scanf (" %c", &valB); // It is " %c". There is a space character in front of %c.
printf ("valB=%c\n", valB);
return 0;
}
Solution3: Read out the "\n" by getchar();
#include <stdio.h>
int main(int argc, char **argv)
{
int valA;
char valB;
scanf ("%d", &valA);
getchar();
printf ("valA=%d\n", valA);
scanf ("%c", &valB);
getchar();
printf ("valB=%c\n", valB);
return 0;
}
沒有留言:
張貼留言