[英]Reading input from a file
LIST.TXT
first 10
second third 20
fourth fifth 30
.
.
.
將第一行與其他行分開讀取的常規方法是什么,這樣我可以使用“第一”,“第二”,......和10,20,......作為程序中其他地方的各自類型?
謝謝!
這是你在想什么?
ifstream fin("list.txt");
string str1, str2;
int n;
fin >> str1 >> n; // first 10
// do something with "first" and 10
while(fin >> str1 >> str2 >> n)
{
// do something with str1, str2 and n
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.