0

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?

DomX23
  • 777
  • 5
  • 12
  • 26
  • 1
    possible duplicate of [How to split a string in C++?](http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) – talnicolas Mar 09 '12 at 01:17
  • 3
    Please read [Why is `iostream::eof` inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Xeo Mar 09 '12 at 01:21

3 Answers3

2

Let the standard stream do it for you:

inputData >> numberOfSiblings >> age;
amdn
  • 10,570
  • 28
  • 42
  • This is great and works, but now it causes a weird bug where the last line gets read twice for some reason... Any idea why? – DomX23 Mar 09 '12 at 02:36
  • @DomX23 - because your input loop in incorrect. Don't use `eof()` or `good()` as the loop condition. Prefer: `while(inputData >> numberOfSiblings >> age) { /* work goes here */ }`. – Robᵩ Mar 09 '12 at 03:42
  • Only reason I can't do that is because the first line I'm taking a different input of int numberOfPeople while the rest of the data file contains numberOfSiblings and age. So I do a check to see if we are on line 1 if so I grab the numberOfPeople and if we are on line>1 I grab the rest. Is there another way to do this rather than using eof()? – DomX23 Mar 09 '12 at 03:54
1

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;
Jerry Coffin
  • 437,173
  • 71
  • 570
  • 1,035
0

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.

kkkkkk
  • 312
  • 5
  • 12