我怀疑cin如何使用两个语句,在我的程序中我首先需要得到一个来自用户的数字序列并将它们放在一个向量中,然后在一个数字B之后将第一个B加起来该向量的元素,例如,如果用户输入序列5,4,3,2,1和B进入3,那么程序将总和5,4和3.但问题是第二个用户输入A将值传递给B,我使用while循环将值序列输出到A但是从第二个值cin到B然后我得到一个out_of_range错误,这是我的代码:
#include "std_lib_facilities.h"
using namespace std;
vector<int> nums;
void sum();
int main()
{
int a;
cout << "Please enter some numbers (press | at prompt to stop)" << endl;
while(cin>>a) nums.push_back(a); //get a series of numbers
sum();
}
void sum()
{
int b,c = 0;
cout << "Please enter how many of the numbers you wish to sum, starting from the first" << endl;
cin>>b; //get the number of elements the user wants to sum
for(int i = 0; i < b+1; ++i){
c += nums[i];
}
cout << "The sum of the first " << b << " numbers is " << c << endl;
}
正确的代码
#include "std_lib_facilities.h"
#include <limits>
using namespace std;
vector<int> nums;
void sum();
int main()
{
int a;
cout << "Please enter some numbers (press | at prompt to stop)" << endl;
while(cin>>a){
nums.push_back(a);
}
cin.clear(); // HERE IS WHAT
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); // WAS MISSING
sum();
}
void sum()
{
int b,c = 0;
cout << "Please enter how many of the numbers you wish to sum, starting from the first" << endl;
cin>>b;
for(int i = 0; i < b; ++i){
c += nums[i];
}
cout << "The sum of ";
for(int d = 0; d < b; ++d){
if(d == b-1) cout << " and " << nums[d];
else cout << nums[d] << " ";
}
cout << " is " << c << endl;
}
答案 0 :(得分:0)
输入|
将设置失败位,并且尾随换行符仍然在流中。
如此清晰的标记并在oder中使用换行符重新启用b
的输入
#include <limits>
// ....
while(cin>>a) nums.push_back(a);
cin.clear ( );
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n') ;
sum();
此外,您应该总结到i < b
而不是i < b+1