list.txt
first 10
second third 20
fourth fifth 30
.
.
.把第一行和其他行分开阅读的常规方法是什么,这样我就可以用" first ","second",……还有10,20,...在程序中的其他地方作为它们各自的类型?
谢谢!
发布于 2012-10-18 13:21:42
struct header {
std::string name;
int number;
};
std::istream &operator>>(std::istream &is, header &h) {
return is >> h.name >> h.number;
}
struct line {
std::string first;
std::string second;
int number;
};
std::istream &operator>>(std::istream &is, line &data) {
returns is >> data.first >> data.second >> data.number;
}
int main() {
header h;
std::ifstream data("list.txt");
// read first line:
data >> h;
// now h.name and h.number are the string and number from the first line
// read the rest of the lines:
std::vector<line> lines((std::istream_iterator<line>(data),
std::istream_iterator<line>());
// now lines[i].first, lines[i].second and lines[i].number
// are the first string, second string, and number
// from the i-th line of three-field data from the file.
return 0;
}https://stackoverflow.com/questions/12947541
复制相似问题