1

what I want to do is input characters in character array in loop .I am new to c programming and don't know uses of pointers very well.my input is something like this :

INPUT:
a b
c d
e f upto n times

I have declared two arrays char a[n],b[n]; and I want to input a in a[0], b in b[1], c in a[2]...

Here is my attempt

char a[n],b[n];
for(i=0;i<n;i++)
{
  scanf("%c %c",&a[i],&b[i]);
  printf("%c %c",*(a+i),*(b+i));
}

but this doesn't work!!if I input: a b the output is a a `

2
  • 2
    "It doesn't work" is a bit vague. What happens? What does it display? Commented Jun 8, 2014 at 14:31
  • Now its working but the output and input have one extra line in between. but I haven't used any newline character? Commented Jun 8, 2014 at 14:50

2 Answers 2

2

If I run your code I get

a b
a bc d

 c  d

which means, that the enter you press after each line, will be interpreted as an input character by scanf(), since you told her to read characters. Also, I had n = 3, but the loop run twice, which also supports this idea.

You should change your scanf() to this:

scanf(" %c %c",&a[i],&b[i]);

which will eat the newline.

Here is a minimal example:

int main(void) {
  int n = 3;
  int i;
  char a[n],b[n];
  for(i=0;i<n;i++) {
    scanf(" %c %c",&a[i],&b[i]);
    printf("%c %c\n",*(a+i),*(b+i));
  }
  return 0;
}

Output:

a b
a b
c d
c d

The newline in printf() is just for formatting elegance, not something more, like a comment had wrongly suggested.

If you want, you can read my page:

Caution when reading char with scanf (C)

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

1 Comment

You are welcome @user3654540, I see you got down-voted, but I think this is something a person who has never sees it can't easily deal with, so I am upvoting you.
0

%c does not skip newlines. So your second scanf will first read the newline at the end of the first line instead of the 'c'.

You could change the scanf to scanf("%1s %1s", &a[i], &b[i]); but then you'll have to increase the size of the arrays by one.

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.