Why the code will skip getline and go to the next code - C++

Viewed 23

I tried to input a string with spaces into a string variable. So I used std::getline. But the line of code doesn't work, it directly skips to the next input. Why is it the case? I attached my code here. This code is in a function. Wherever I put the getline code, it will skip and run the next line. In the case I provided, after I input the name and press enter, it will skip the sex input and arrive at the age input.

I also tried to test it in the main function directly and it works, which is even more confusing for me. Thank you so much for your help!

Input a name: name
Input sex: Input age:
    cout << "Input a name: ";
    //getline(cin, c->book[c->size].name);
    cin >> c->book[c->size].name;
        
    cout << "Input sex: ";
    getline(cin, c->book[c->size].sex);
    //cin >> c->book[c->size].sex;
        
    cout << "Input age: ";
    cin >> c->book[c->size].age;
        
    cout << "Input phone #: ";
    cin >> c->book[c->size].number;
    
    cout << "Input address: ";  
    //std::getline(cin, c->book[c->size].address);
    cin >> c->book[c->size].address;
0 Answers
Related