M
main()
I know this is the problem that most newbies get into.
#include<stdio.h>
int main(void)
{
char a;
scanf("%c",&a); /*1st scanf */
printf("%c\n",a);
scanf("%c",&a); /*2nd scanf*/
printf("%c\n",a);
return 0;
}
This will not work, because after the first scanf a newline is left
behind in the input stream, unconsumed.
I made this attempt to solve this problem
#include<stdio.h>
int main(void)
{
char a,b;
scanf("%c",&a);
printf("%c\n",a);
getchar(); /* putting getc(stdin) also worked*/
scanf("%c",&a);
printf("%c\n",a);
return 0;
}
Out of curiosity I tried this also,
#include<stdio.h>
int main(void)
{
char a,b;
scanf("%c",&a);
printf("%c\n",a);
scanf("\n%c",&a);
printf("%c\n",a);
return 0;
}
which gave me expected output.
But my question is (finally!) , why the following code doesn't work,
#include<stdio.h>
int main(void)
{
char a,b;
scanf("%c\n",&a); /* 1st scanf */
printf("%c\n",a);
scanf("%c",&a); /* 2nd scanf */
printf("%c\n",a);
return 0;
}
My assumption was 1st scanf will consume the newline left in the input
stream.
Thanks for your time,
Yugi.
#include<stdio.h>
int main(void)
{
char a;
scanf("%c",&a); /*1st scanf */
printf("%c\n",a);
scanf("%c",&a); /*2nd scanf*/
printf("%c\n",a);
return 0;
}
This will not work, because after the first scanf a newline is left
behind in the input stream, unconsumed.
I made this attempt to solve this problem
#include<stdio.h>
int main(void)
{
char a,b;
scanf("%c",&a);
printf("%c\n",a);
getchar(); /* putting getc(stdin) also worked*/
scanf("%c",&a);
printf("%c\n",a);
return 0;
}
Out of curiosity I tried this also,
#include<stdio.h>
int main(void)
{
char a,b;
scanf("%c",&a);
printf("%c\n",a);
scanf("\n%c",&a);
printf("%c\n",a);
return 0;
}
which gave me expected output.
But my question is (finally!) , why the following code doesn't work,
#include<stdio.h>
int main(void)
{
char a,b;
scanf("%c\n",&a); /* 1st scanf */
printf("%c\n",a);
scanf("%c",&a); /* 2nd scanf */
printf("%c\n",a);
return 0;
}
My assumption was 1st scanf will consume the newline left in the input
stream.
Thanks for your time,
Yugi.