Reputation: 21
Why does this for
only runs 5 times? As in it gets 5 character and then stops. And if I change the i<10
to i<5
it only runs 3 times.
#include <stdio.h>
char a[1000];
int main()
{
char a[100];
for(int i=0;i<10;i++)
{
scanf("%c",&a[i]);
}
}
Upvotes: 1
Views: 62
Reputation: 409404
I think the problem is most likely that you don't think the Enter key will give you a character, but it will result in a newline '\n'
character.
If you want to skip the newlines (or really any white-space) then use a leading space in the scanf
format string:
scanf(" %c",&a[i]);
// ^
// Note space here
If you want to read other space characters (like "normal" space or tab) then you need to use one of the character-reading functions like fgetc
or getchar
. For example as
for (size_t i = 0; i < 10; ++i)
{
int c = getchar();
if (c == '\n')
continue; // Skip newline
if (c == EOF)
break; // Error or "end of file"
// Use the character...
}
Upvotes: 5