我正在努力处理 vector push_back 函数。 目标是拥有一个推送 n 个元素的功能,直到您决定停止。 所以我认为“停止”是 cin.fail()。
错误的功能是
void pushbackVector(vector<double> &data)
{
double input;
cin >> input;
for (int i = 0; i < 100; i++)
{
if (cin.fail())
{
cout << "Ending input.\n";
return;
}
else
{
data.push_back(input);
}
}
问题是当我尝试使用它时,我进入了一个无限循环。
我还没有按 ASC 顺序对第一个 vector 进行排序,按 DESC 顺序对第二个 vector 进行排序,并将第一个和第二个 vector 连接到第三个 vector 中。但是我有信心我可以自己管理它。 不管怎样,整个代码....
#include<iostream>
#include<vector>
#include<algorithm>
#include<cctype>
using namespace std;
// function prototypes
void menu();
void printVector(const vector<double> &data);
void pushbackVector(vector<double> &data);
void sortVector (vector<double> &data);
int main()
{
menu();
vector<double> row1;
vector<double> row2;
/* not yet used
vector<double> row3;
*/
int input;
cin >> input;
bool exit = 0;
while (!exit)
{
switch (input)
{
case 1:
pushbackVector(row1);
break;
case 2:
pushbackVector(row2);
break;
case 3:
printVector(row1);
break;
case 4:
printVector(row2);
break;
case 5:
cout << "Printing out the contents of row 1\n";
printVector(row1);
cout << "Printing out the contents of row 2\n";
printVector(row2);
cout << "Printing out the contents of row 3\n";
// printVector(row3);
break;
case 6:
cout << "Exitting\n";
exit = 1;
break;
default:
cout << "Invalid choice\n";
}
}
return 0;
}
void menu()
{
cout << "Choose an option\n";
cout << "1) Enter first vector\n";
cout << "2) Enter second vector\n";
cout << "3) Print out the first vector\n";
cout << "4) Print out the second vector\n";
cout << "5) Print out all three vectoros\n";
cout << "6) Exitting the program\n";
}
void printVector(const vector<double> &data)
{
for(int i = 0; i < data.size(); i++)
{
cout << data[i] << ", ";
}
cout << "\n";
}
void pushbackVector(vector<double> &data)
{
double input;
cin >> input;
for (int i = 0; i < 100; i++)
{
if (cin.fail())
{
cout << "Ending input.\n";
return;
}
else
{
data.push_back(input);
}
}
}
void sortVector (vector<double> &data)
{
cout << "Sorting your vector \n";
sort(data.begin(), data.end());
}
最佳答案
您只读取一次,将读取移动到循环内:
void pushbackVector(vector<double> &data)
{
double input;
// cin >> input; --------------
//
for (int i = 0; i < 100; i++) //
{ //
cin >> input; // <---------
if (cin.fail())
{
cout << "Ending input.\n";
return;
}
else
{
data.push_back(input);
}
}
这将确保您真正获得输入。现在,如果您不打算输入 100 个值,则需要以某种方式通知流。这是通过在其中插入“EOF 字符”来完成的。在 Windows 上按 CTRL+Z 或在 unix 终端上按 CTRL+D。
当它从流中读取时,它进入一个 fail
(和 eof
)状态,它将保持这种状态,除非您通过调用 cin.clear()
清除错误标志在适当的时候。
你在 main 中也犯了同样的错误。您只在 while
之前阅读过一次循环,所以 input
保留您最初输入的值并继续输入相同的选择。我认为这就是你所说的无限循环。要修复它,请将读取语句移动到 switch
之前.
希望对您有所帮助。
此外,这就是我编写函数的方式:
double input;
for (int i = 0; (cin >> input) && i < 100; ++i) {
data.push_back(input);
}
cout << "Ending input.\n";
流可用于 bool 表达式 - 它们转换为 !fail()
的结果- 这是控制循环的一种方便且惯用的方法。
关于c++ - 使用 cin::fail() 从 stdin 读取无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20658562/