简体   繁体   中英

using getline(cin, string) on a loop not working properly

I am using a for loop to input data in a structure array, I am not able to get a string variable to have white spaces, such that the stored name is two or more words as opposed to one. Can anyone help me properly use getline in a loop?

It works when I do not use a loop, not sure what is causing the error in this program though.

Below is the sample that is giving me trouble:

void Data_Input(int numberOfStudents, int numberOfTests, classroom* &student){
    for (int count = 0; count < numberOfStudents; count++){
        cout << "For student number " << count + 1 << 
                ", please input the following data:";
        cout << "Student Name: ";
        //cin >> student[count].Name; (this option does not allow white spaces)
        getline(cin, student[count].Name); // <-- this line 
    }
}

I've modified your program slightly so that I could test your function and I couldn't find any problems with what I expect the behavior to be, could you elaborate one what you're trying to accomplish?

The way your code is currently formatted, I expect that student[count].Name is an std::string .

#include <iostream>

void Data_Input(int numberOfStudents, int numberOfTests){

    for (int count = 0; count < numberOfStudents; count++){
        std::cout << "For student number " << count + 1 << ", please input the following data:";
        std::cout << "Student Name: ";
        //cin >> student[count].Name; (this option does not allow white spaces)
        std::string student;
        getline(std::cin, student);


        std::cout << student << std::endl;
    }
}

int main() {

    Data_Input(5, 0);

}

runtime:

For student number 1, please input the following data:Student Name: John Smith
John Smith
For student number 2, please input the following data:Student Name: Anne Smith
Anne Smith
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM