2

I have written this code to input two array of characters a and b of size 5 each.

When I give the input :

abcde
abcde

the output b[2] should be c but it is giving as b.

#include <stdio.h>

using namespace std;

int main(){

   char a[5], b[5];
   int i;
   for(i = 0; i < 5; i++){
       scanf("%c", a + i);
   }

   for(i = 0; i < 5; i++){
       scanf("%c", b + i);
   }

    printf("%c", b[2]);
}
3
  • Then how i avoid this Commented Oct 2, 2015 at 11:01
  • 2
    Pick a language. C doesn't have namespace std, and in C++ you'd use std::cin >> Commented Oct 2, 2015 at 11:26
  • see this answer stackoverflow.com/questions/7898215/… Commented Oct 2, 2015 at 13:19

1 Answer 1

2

Remember pressing Enter after typing abcde for the first scanf? This character is consumed by the second scanf during the first iteration of the second for loop.

You can fix it by adding

scanf("%*c");

or

getchar();

between the two for loops. This will scan and discard the newline character.

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

1 Comment

Or, better yet, if your input consists of lines, use an input function that reads lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.