0

Here's my small piece of example code:

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    int num;
    char name[20];
    cout << "How many names: ";
    cin >> num;

    for(int i = 0; i < num; i++)
    {
        cout << "Enter name " << (i+1) << ":";
        fgets(name, 20, stdin);
        cout << name;
    } 
}

Basically I want to input more than 1 name and print it immediately. It's very trivial and I'm only doing it to get a hang of fgets. But I just can't get it to work.

For some reason it doesn't wait for an input after the first name prompt but the inputs after that work great.

I thought maybe it has something to do with the space after the ":" on the first "cout" line in the "for" loop so I removed it but it still doesn't work.

Here's a sample output:

$ ./a.out
How many names: 3
Enter name 1:
Enter name 2:Eric
Eric
Enter name 3:Adam
Adam

Can somebody please help me understand what might be going on here? I went through a bunch of questions on similar topics but I was unable to find an explanation for this behavior. Thanks in advance!

0 Answers0