我使用for循环在结构数组中输入数据,我无法获得具有空格的字符串变量,因此存储的名称是两个或多个单词而不是一个单词。任何人都可以帮助我在循环中正确使用getline
吗?
当我不使用循环时,它可以工作,不知道是什么导致了这个程序中的错误。
以下是给我带来麻烦的样本:
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
}
}
答案 0 :(得分:0)
我已稍微修改了您的程序,以便我可以测试您的功能,但我无法发现任何与我期望的行为有关的问题,您是否可以详细说明您尝试的内容完成?
您的代码目前的格式,我希望student[count].Name
是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);
}
运行时:
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
...