#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct member
{
string name;
double distance = -1;
};
int main()
{
int n;
cin >> n;
vector<member> a(n);
for (size_t i = 0; i < n; i++)
{
//cin.clear()
for (size_t z = 0; z < 3; z++)
{
string inp;
cin >> inp;
a[i].name += " " + inp;
}
for (size_t j = 0; j < 6; j++)
{
double input;
cin >> input;
if (input > a[i].distance)
a[i].distance = input;
}
}
}
我的输入数据示例(3 个单词,然后是 6 个数字或“x”):
8
GER Christian Reif 8.18 x 8.22 8.12 8.12 7.96
RSA Godfrey Mokoena 8.00 7.91 7.87 7.93 8.01 8.10
BRA Mauro Silva x x 8.09 8.05 8.23 8.24
MEX Luis Rivera 7.92 8.16 8.17 8.03 8.27 x
ESP Eusebio Caceres 8.09 8.25 8.17 x 8.26 8.20
RUS Aleksandr Menkov 8.14 7.96 8.52 8.43 8.56 x
JAM Damar Forbes 8.02 7.89 x x 8.00 x
NED Ignisious Gaisah 8.09 8.15 8.17 8.29 x 8.16
但是,如果我将此数据提供给程序的输入,那么它只考虑
8
GER Christian Reif 8.18 x 8.22 8.12 8.12 7.96
我找到了解决它的方法—— cin.clear()(我把它注释掉了)。但是问题。这个问题的原因是什么?为什么要cin.clear()修?
您正在
double尝试输入一个 character'x',因此cin它进入状态fail(constantfailbit) 并且不能再读取数据,cin.clear()将流的状态从failtogood(constantgoodbit) 恢复,之后cin它可以再次读取数据。https://en.cppreference.com/w/cpp/io/basic_ios/clear
正确的输入是逐行使用
std::getline(),然后逐行解析结果行,再次逐行解析。从 3 个单词开始,std::stod用于检查异常。那么就不会因为输入而出现问题。