Reputation: 3878
list.txt
first 10
second third 20
fourth fifth 30
.
.
.
What's the conventional way to read the first line separately from the others, such that I can use "first","second", ... and 10, 20, ... as their respective types elsewhere in the program?
Thanks!
Upvotes: 1
Views: 96
Reputation: 490048
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;
}
Upvotes: 0
Reputation: 99084
Is this what you're thinking of?
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
}
Upvotes: 3