-1

So I have this code:

char inputs[10] = "";
int numInputs = 0;
while (numInputs < 10){
    char c;
    printf("Enter char %i: ",numInputs);
    scanf("%c",&c);
    numInputs++;
}

I'm just trying to fill the array with 10 char values as inputted by the user. When i run this, it only lets me enter inputs ever other loop (?). This is what the console looks like-

Enter char 0: c Enter char 1: Enter char 2: r Enter char 3: Enter char 4: r Enter char 5: Enter char 6: r Enter char 7: Enter char 8: r Enter char 9: Program ended with exit code: 0

Is there a nit-picky thing here that i'm missing?

Jordan
  • 445
  • 2
  • 10
  • 21
  • 2
    Possible duplicate of [What does space in scanf mean?](http://stackoverflow.com/questions/6582322/what-does-space-in-scanf-mean) – Billal Begueradj Feb 24 '16 at 05:49
  • 3
    You should learn how to debug your code. Here's a good intro: http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Paul Hankin Feb 24 '16 at 06:36

2 Answers2

1

Change

scanf ("%c", &c);

to

scanf (" %c", &c);

As @haris mentioned, the space is used to consume the \n (newline) left in the input buffer caused by the previous scanf.

Also see: What does space in scanf mean?

Community
  • 1
  • 1
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
  • Thanks! This worked. Why exactly is the extra space required? – Jordan Feb 24 '16 at 05:46
  • If I am not mistaken, it's because you added the extra space? Try changing `printf("Enter char %i: ",numInputs);` to `printf("Enter char %i:",numInputs);` . It may be hard to see, but after %i: it seems you have a space that scanf() is reading? – daniel.caspers Feb 24 '16 at 05:48
  • 2
    @Jordan, space is used to consume the left out newline character `\n` in the input buffer after the previous `scanf`s. – Haris Feb 24 '16 at 05:50
  • @Haris, would you typically then just scan a newline character instead? Something like `scanf ("%c\n", &c);`? EDIT: Disregard, saw other answer just come in. – daniel.caspers Feb 24 '16 at 05:54
0

The below code should work fine. scanf waits for input on a new line. Since you were not returning to a new line it was reading already existing space character on the current line.

 char inputs[10] = "";
    int numInputs = 0;
    char c;
    while (numInputs < 10){
        printf("Enter char %i: ",numInputs);
        scanf("%c\n",&c);
        numInputs++;
    }
Rohit Magdum
  • 104
  • 4