Reputation: 887
I'm using getline to grab lines from an input data file that looks like this
1 9
5 5
6 7
...
Where the first number the number of siblings someone has and the second number is someone's age.
const int MAXLINE=50;
int main(int argc, char *argv[]) {
int numberOfSiblings;
int age;
char oneline[MAXLINE];
ifstream inputData;
inputData.open(argv[1]);
while ( !(inputData.eof()) ) {
inputData.getline(oneline, MAXLINE);
numberOfSiblings = oneline[0] - '0';
age = oneline[2]-'0';
}
}
Howerver, I can't assume that those ints will always be at the same index due to white space.
Since if there are two spaces rather than one age will now be in index 3. How can I account for this?
Also, what happens if I have a double digit number?
Upvotes: 0
Views: 675
Reputation: 692
There has been many good answers.
But, I think if you want to use&learn C++,
you'd better use '<<' or '>>' to help you to do your job.
In answers, they used override operator, you can learn from HERE || HERE.
Upvotes: 0
Reputation: 490078
std::istream already has operator>>
to skip across any leading whitespace, then read an int for you. That seems to be what you need, so I'd just use it.
If I were doing this, I'd start with a structure to represent one person's data:
struct data {
int num_siblings;
int age;
};
Then I'd write a function to read one of those items:
std::istream &operator>>(std::istream &is, data &d) {
return is >> d.num_siblings >> d.age;
}
With that, you can read a data
item from a stream using operator>>
:
std::ifstream input("people.txt");
data person;
input >> person;
Upvotes: 1
Reputation: 11582
Let the standard stream do it for you:
inputData >> numberOfSiblings >> age;
Upvotes: 2