如何构建while循环,以便在用户输入0之前保持接受int值?
我有
while(cin >> integers && integers != 0){
numbers.push_back(integers);
if(integers == 0){
break;
}
}
但它一直让我崩溃。
编辑:
int integers;
int fox;
vector<int> numbers;
cout << "Please enter in integers (0 to stop): ";
while(cin >> integers){
numbers.push_back(integers);
if(integers == 0){
break;
}
}
int y = numbers.size();
for(int i = 0; i < y; y++){
cout << numbers.at(y) << " ";
}
答案 0 :(得分:2)
y
应为i
。您正在访问向量越界。此外y++
应为i++
,否则您将无限循环。
for (std::vector<int>::size_type i = 0; i < members.size(); i++) {
cout << numbers.at(i) << " ";
}
operator[]
没有边界检查,所以at
实际上在这方面更安全。
Visual Studio可能因为你的无限循环而导致abort
,或者因为你有一个未被捕获的out_of_range
异常。例如,它可能如下所示:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
这是不必要的,但您可以将代码包装在try-catch块中。
try
{
std::cout << members.at(members.size());
} catch(std::out_of_range& ex)
{
std::cout << "Out of range error: " << ex.what() << "\n";
}
答案 1 :(得分:0)
以下是基于您的问题的示例。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers;
int integers;
while(cin >> integers && integers != 0){
numbers.push_back(integers);
}
for( int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i] << ' ';
return 0;
}
看到您编辑的问题后。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int integers;
int fox;
vector<int> numbers;
cout << "Please enter in integers (0 to stop): ";
while(cin >> integers){
if(integers == 0){
break;
}
numbers.push_back(integers); //Moved after the check to not inclue 0
}
int y = numbers.size();
for(int i = 0; i < y; i++){
cout << numbers[i] << " ";
}
return 0;
}