Getting input for character arrays
I was coding a program to find the longest common sub-sequence today and I was getting the elements of the each sequence into a character array. but I ran into a little problem. I used a for loop to get the elements but not matter how high I set the number of iterations the loop should execute it always terminated after 5 iterations. The array into which the data was being input was an array of size 10 so there were no issues with 开发者_JAVA技巧the array size. I coded a small test program to check and even in the test program the for loops that get data for a character array always terminate after 5 iterations . Why ?( I am forced to use turbo c++ in my lab)
#include<stdio.h>
void main()
{
int i;
char s[10];
for(i=0;i<10;i++)
scanf("%c",&a[i]);
}
The above code was the test program.for loop terminated after 5 iterations here too !
Newline characters ('\n'
) are characters too. If you type H
, <return>
, e
, <return>
, l
, <return>
, l
, <return>
, o
, <return>
, they you've entered 10 characters.
It's a much better idea to just read the entire "array" as a single string, all at once:
char s[10];
fgets(s, sizeof s, stdin);
Let me guess, you're pressing return
after each character? The scanf()
call will read those too...
精彩评论