0

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 !

2
  • 5
    sigh at least try to compile the code before you post it. also, the loop definitely doesn't terminate after 5 iterations, you should have put some trace message there to see it :/ Commented Sep 23, 2011 at 14:02
  • ok i did compile it. and i tried displaying i after ever scanf statement. but it just kept incrementing twice . Commented Sep 23, 2011 at 14:06

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.