2014-05-06 56 views
0

我正在使用for循环在结构数组中输入数据,我无法获得具有空格的字符串变量,以便存储名称是两个或两个以上的词,而不是一个。任何人都可以帮助我在一个循环中正确使用getline在循环中使用getline(cin,string)无法正常工作

它工作时,我不使用一个循环,不知道是什么导致在这个程序中的错误,虽然。

下面是给我找麻烦样本:

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

你至少应该检查输入通过'如果成功(函数getline(...))'。 – chris

回答

0

我稍微修改程序,这样我可以测试你的功能,我找不到任何问题,我所期望的行为是的,你能否详细说明你正在努力完成的任务?

您的代码目前已格式化的方式,我预计student[count].Namestd::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 
...