Strings and Ints Pointer Help

I put some code below to show exactly what I'm stumped with. After the first time the loop in the function getNames happens, I can no longer type in a name. It instead skips right to the number part and skips the name entirely. Just wondering why it's doing that. Very frustrating. Also, I just started learning pointers so I'm definitely not the best with them.

Thank you ahead of time for help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>

using namespace std;

void getNames(string *, int, int *);

int main()
{
    int x = 2;
    
    int *nums;
    string *names;
    names = new string[x];
    nums = new int[x];

    getNames(names, x, nums);

    for (int i = 0; i < x; ++i)
        cout << names[i] << " " << nums[i] << endl;
}

void getNames(string *name, int size, int *number)
{
    for (int i = 0; i < size; ++i)
    {
        cout << "Name " << i + 1 << ": ";
        getline(cin, name[i]);
        cout << "Number " << i + 1 << ": ";
        cin >> number[i];
    }
}
Last edited on
cin >> number[i]; leaves a newline in the stream which getline() interpretes as an empty line.

Use ignore() with '\n' after line 30


http://www.cplusplus.com/reference/istream/basic_istream/ignore/
Topic archived. No new replies allowed.