I'm new to C and I'm trying to understand how the for loops work.
My code looks like this
#include <stdio.h>
int main ()
{
int a;
for( a = 0; a < 4; a++ )
{
printf("value of a: %d\n", a);
}
return(0);
}
I get my expected output which is 4 times the value of a but when I do this
#include <stdio.h>
int main ()
{
char c;
int a;
for( a = 0; a < 4; a++ )
{
printf("value of a: %d\n", a);
printf("Enter character: ");
c = getchar();
printf("Character entered: ");
putchar(c);
printf("\n");
}
return(0);
}
I get
value of a: 0 Enter character: m Character entered: m value of a: 1 Enter character: Character entered:
value of a: 2 Enter character: a Character entered: a value of a: 3 Enter character: Character entered:
It somehow over jumps the two of the getChar()
, why?
SOLUTION Go it to work thanks to the comments:
int i;
for( a = 0; a < 4; a++ )
{
printf("Enter character: ");
c = getchar();
while ((i = getchar()) != '\n' && i != EOF)
printf("Character entered: ");
putchar(c);
}
As pointed out in comments, the ENTER
key results in as a newline (\n
) character, and getchar
reads and returns it after each letter.
You also should pay attention to errors or end-of-file conditions.
Here's a more robust version:
#include <stdio.h>
int main ()
{
char c;
int a;
for(a=0; a<4; a++)
{
printf("value of a: %d\n", a);
printf("Enter character: ");
do {
c = getchar();
} while(c == '\n'); // ignore newlines
if(c == EOF) break; // end of input or error
printf("Character entered: %c\n",c);
}
return(0);
}
This has the added benefit (or not) that duplicated ENTER keys are ignored. Also, if you type two characters before the ENTER, they will be both read the same as if each were typed separatedly. Again, this might be good or not, depending on what you want to happen. But you should ask yourself what do you want to happen.