【发布时间】:2017-10-01 19:01:33
【问题描述】:
我已经尝试了很多方法并不断更改此代码,但我无法让它停止在它接受“分数”值之前需要两个输入。此外,我一直无法找到一种方法来阻止 cin 从“得分”和“答案” 从允许用户在不输入值的情况下按 Enter 键。我见过的唯一方法是将它们都作为字符串接受,但我希望避免这种情况。
#include<iostream>
#include<iomanip>
#include<limits>**strong text**
using namespace std;
//void enterdata(string*, int*);
int main(){
// string names[];
// int testscores[];
string name;
int score;
char answer;
cout<<"This program asks the user to enter a list of names and test scores,"<<endl;
cout<<"then sorts the list into ascending order according to the scores"<<endl;
cout<<"and calculates the average test score."<<endl;
// enterdata(names, testscores);
do{
cout<<"Please enter a name: ";
getline(cin, name);
while(name.empty()){
cout<<"No entry detected. Please enter a name: ";
getline(cin, name);
}
cout<<name<<endl;
cout<<"Please enter a test score: ";
cin>>score;
while(!(cin>>score) || score<0){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"Input not valid. Only positive integers will be accpeted."<<endl;
cout<<"Please enter a test score: ";
}
cout<<score<<endl;
cin.sync();
cout<<"Would you like to enter another student name and test score? [y/n] ";
cin>>answer;
while(answer!='y' && answer!='n'){
cout<<"Input not valid. Only y or n will be accepted."<<endl;
cout<<"Would you like to enter another student name and test score? [y/n] ";
cin>>answer;
}
cout<<answer<<endl;
cin.sync();
} while(answer == 'y');
return 0;
}
【问题讨论】:
-
我不知道。它似乎与那个问题不同。它没有跳过输入。如果不接受值,程序将不会进入下一步。只要我输入一个正数并回车,我第二次输入一个数字并回车时,cin 接受一个值并继续程序的下一步。
-
您在这两行中读取了两次整数 - cin>>score; while(!(cin>>score) || score
-
好的,@Harmeet,那么这不是运行错误检查的适当语句吗?声明 !(cin>>score) 似乎每次我输入数字以外的内容时都会为我捕捉到错误。比如说,我按字母 f 获取考试成绩,它会立即抛出无效语句并告诉我重新输入考试成绩。当我尝试输入整数时,我似乎只有双重输入问题。我应该输入其他声明/条件吗?