2014-04-14 46 views
0

我在循环中使用getline()。在第一个循环中,除了最后一个getline()外,所有内容都运行正常。在第二个循环中,第一个getline()似乎已被跳过。下面是环:如何在循环中使用getline C++

while(true) 
    { 
     cout <<endl<< "Enter Student's Name: "; 
     getline(cin,tmp_name); 
     cout << "Enter Student's RegNo: "; 
     getline(cin,tmp_regno); 
     cout << "Enter Student's marks: "; 
     cin>>tmp_marks; 
     mystudents.push_back(student(tmp_name,tmp_regno,tmp_marks)); 
     mystudents[no_ofStudents].getGrade(); 
     no_ofStudents++; 
     cout<<endl<<endl<<"Do you wish to continue? To continue enter yes or any other key to stop: "; 
     getline(cin,continue_stop); 
     if (continue_stop!="yes"&&continue_stop!="YES") 
      break; 
    } 
+1

是什么类型continue_stop? – 4pie0

+0

请显示所有相关数据类型! –

+0

这些是数据类型: int no_ofStudents = 0; string tmp_name; int tmp_marks; string tmp_regno; vector mystudents; –

回答

1
cin >> tmp_marks; 

离开换行符( '\ n')的输入流。你必须想出一种方法来阅读所有内容,直到下一个换行符。

1

而另一件事

if (continue_stop!="yes"&&continue_stop!="YES") 
    break; 

这将打破while循环在错误的时间。

+0

这是不正确的,输入yes/YES打破循环 – 4pie0

+0

我使用YES或yes来允许用户通过退出循环或继续输入数据来停止输入数据 –

0
cin >> tmp_marks; 

叶输入流'\n'和您正在阅读它在未来的阅读

std::getline(std::cin,continue_stop); 

可以忽略这个角色搭配:

std::cin>>tmp_name; 
    std::cin.ignore(); 
    std::cout<<std::endl<<std::endl<<"Do you wish to continue?"; 
    std::getline(std::cin,continue_stop); 
    if (continue_stop!="yes"&&continue_stop!="YES") 
     break; 
相关问题