我正在处理正在处理的项目的cin
命令问题。
在下面的代码中,命令要求用户输入1再次尝试或2退出,我有命令cin >> keepGoing;
出于某种原因,这完全被跳过了。我已经尝试清除缓冲区并使用cin.clear();
而没有运气。这是代码:
int searchDisplay()
{
bool flag = false;
vector<Client> store;
Client foo;
int i = 0;
int totalIt = 0;
Client search;
char response;
int keepGoing;
string input;
fstream customer("customer.dat", ios::in);
if (!customer)
{
cout << "Error opening file. Program aborting." << endl;
return 0;
}
i = 0;
while (!customer.eof())
{
store.push_back(foo);
customer.read(reinterpret_cast<char *>(&store[i]),
sizeof (store[i]));
i = i + 1;
}
totalIt = i;
while (flag == false)
{
i = 0;
cout << store[i].name << endl; //test to see what is in store at i = 0
cout << "Name: " << endl;
cin >> search.name;
while (i < totalIt - 1)
{
if (search.name == store[i].name)
{
flag = true;
cout << "Name: " << store[i].name << endl
<< "Address 1: " << store[i].address1 << endl
<< "Address 2: " << store[i].address2 << endl
<< "Phone: " << store[i].phone << endl
<< "Account Balance: " << store[i].acctBal << endl
<< "Last Payment: " << store[i].lastPay << endl;
cout << endl << "Strike any key to continue";
cin.get(response);
}
else
{
i = i +1;
cout << "searched " << i << "times" << endl;
}
}
if (flag == false)
{
cout << "There is no record of that name in our files. Hit 1
to try again or any number to quit:" << endl;
cin.clear();
cin >> keepGoing; //HERE IS MY PROBLEM
if (keepGoing != 1)
{
flag = true;
}
else
{
flag = false;
}
}
}
customer.close();
return 1;
}
我发现有类似问题的所有其他问题的答案要么不起作用,要么导致我无法弄清楚的错误。希望我的编码能够帮助您找到更加个性化的答案。谢谢你的帮助。
答案 0 :(得分:0)
适合我:(
(对不起,我应该发表评论,但我是新人,我的代表很可怕。)
我尝试使用虚拟Client
类和一些#includes
(以及一个customer.dat文件并注释掉cout << store[i].name << endl; //test to see what is in store at i = 0
)...
它有效。 <击> 100%撞击>
如果我没有输入1
,那就崩溃了。但如果关键是它正在阅读cin >> keepGoing;
就好了。
看起来您的代码很好。希望这在某种程度上有所帮助。
P.S。:我的包括因此:
#include <vector>
#include <fstream>
#include <iostream>