Srini
Srini

Reputation: 1649

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 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 !

Upvotes: 0

Views: 123

Answers (3)

Kusalananda
Kusalananda

Reputation: 15633

Let me guess, you're pressing return after each character? The scanf() call will read those too...

Upvotes: 1

unwind
unwind

Reputation: 400109

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);

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272772

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.

Upvotes: 2

Related Questions