我的目的是,每当输入 {“name”,number} 这样的组时,就显示出来,当输入的形式不对时,就结束程序,以下是我的代码
#include <vector>
using namespace std;
struct Entry
{
string name;
int number;
};
ostream& operator<<(ostream& out, Entry a)
{
out << a.name << " " << a.number << endl;
return out;
}
istream& operator>>(istream& in, Entry& a)
{
char c, c2;
if (in >> c && c == '{'&& in >> c2 && c2 == '"')
{
string name;
while (in.get(c) && c != '"')
name += c;
if (in >> c && c == ',')
{
int number = 0;
if (in >> number>>c && c == '}')
{
a = { name,number };
return in;
}
}
}
in.setf(ios_base::failbit); //输入格式不对,将输入流置为failbit
return in;
}
int main()
{
Entry a;
while (cin>>a) //读入Entry对象,故意输错也无法跳出循环
{
cout <<a << endl;
}
system("pause");
return 0;
}
但是在执行的时候,如果输错格式,程序不会停止,而是会不断输出上一次的输入,如下图
总是无法将cin.failbit置位,无法跳出循环
希望高手帮助,多谢!