Americo
Americo

Reputation: 919

C - Duplication of Printf when an array is involved

I hope this isn't too basic of a question for stack overflow. But I have a query which is trying to determine the amount of grades in an array, and then ask for user input of each of those grades. It looks like this:

#include <stdio.h>


int main (void)
{
int size;

printf ("Enter The Amount Of Grades In Your Array: ");
scanf("%i", &size);/*Stores Amount Of Grades In The Array*/

char myGrades[size];
int i;

for (i = 0; i < size; ++i)
  {
  printf ("Enter the grade:");
  scanf ("%c",&myGrades[i]);
  }

return 0; 
}

I expect the first line after int i to read "Enter The Grade:" but instead it looks like "Enter The Grade:""Enter The Grade:"

I don't understand why it says enter the grade the second time without first asking for my input on the first "enter the grade". Any suggestions would be much appreciated!

Upvotes: 1

Views: 54

Answers (1)

teppic
teppic

Reputation: 8195

Your first scanf is leaving the \n behind, and then automatically reading it again the next time as if you'd pressed enter (so the newline is stored in your array). You can get around this by using " %c" instead. The space will get rid of any newlines or spaces before the character you want.

Upvotes: 5

Related Questions