如何将如下格式的文件读入一个结构体? 这是我到目前为止的代码,我无法让它工作。我可以输入整行,但我如何将数据位分开???
New England Patriots 6 2 .750 3-2 3-0 1-0 1 Buffalo Bills 5 2 .714 4-0 1-2 1-0 1
ifstream inFile;
string name1;
string conference1;
string division1;
unsigned short wins1;
unsigned short losses1;
float pct1;
int i = 0;
int count = 0;
// this declares the strings we need
string line = "";
int a = 0;
string temp = "";
inFile.open(filename.c_str());
if (!inFile) {
cerr << "Unable to open file" << filename;
exit(1); // call system to stop
}
if (inFile) {
while (inFile.good())
{
//std::getline(inFile, line, '\t'); this is how you get line skipping tabs
std::getline(inFile, line);
cout << line;
cout << endl;
teams[a].raw = line;
//cout << teams[a].raw;
//cout << endl;
// teams[a].name = line;
teams[a].position = a + 1;
a++;
}
cout << teams[20].raw;
cout << endl;
cout << a - 1;
cout << endl;
}
inFile.close();
struct NFL {
string name;
string conference;
string division;
unsigned short wins;
string win;
unsigned short losses;
string lose;
float pct;
string per;
string home;
string road;
string raw;
int position;
};
struct ExpectedChar { char expected; };
// read a character from a stream and check it has the expected value
std::istream& operator>>(std::istream& in, const ExpectedChar& e)
{
char c;
if (in >> c)
if (c != e.expected) // failed to read expected character
in.setstate(std::ios::failbit);
return in;
}
// read a struct pass from a stream
std::istream& operator>>(std::istream& in, NFL& p)
{
ExpectedChar tab{ '\t' };
in >> p.name >> tab >> p.serviceTime >> tab >> p.classType;
return in;
}
最佳答案
使用std::getline()
以\n
(默认)作为分隔符读取整行,然后使用std::istringstream
解析每一行的值,使用 std::getline()
读取由非空格分隔的字符串数据。
例如:
ifstream inFile(filename.c_str());
if (!inFile) {
cerr << "Unable to open file" << filename;
exit(1); // call system to stop
}
string line;
while (getline(inFile, line))
{
istringstream iss(line);
getline(iss, teams[a].name, '\t');
...
iss >> teams[a].wins;
/* or:
string temp;
getline(iss, temp, '\t');
istringstream(temp) >> teams[a].wins;
*/
... and so on ...
}
关于c++ - 如何将由制表符分隔的文件读入结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47274177/