我对cin如何处理两个语句有疑问,在我的程序中,我需要首先从用户那里获得一个数字序列,并将它们放在一个向量中,在一个数字B之后,它将对该向量的前B个元素求和,例如,如果用户输入序列5、4、3、2、1,然后输入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;
}
输入|
将设置失败位,并且尾部换行符保留在流中。
因此,清除标志并吃掉换行符,以便重新启用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