Use fstream and sstream together to separate strings/integers from file

302 views Asked by At

So I want to take in information from a file, it will start with names(strings) and will eventually change to integers.

Ex. for nums.txt

James Smith
John Jones
Amy Li
1 3 2 3
3 2 4 1 0

I want to write a program that stores each name (one name per line) and then when names end and numbers begin, it starts adding each # occurrence to an array. I.E. if 3 2's appear, i want

numInt[2] to equal 3

I want to do this using an ifstream to take input from a file, and use a stringstream to sort strings and integers. so far I have this

int main() {
 string names[10];
 int numNames = 0;
 int numInt[100] = {};
 ifstream file("nums.txt");
 stringstream ss;
 string s;
 int n;

 while (file >> ss) {
  while (ss >> s) {
   names[numNames] = s;
   numNames++;
  }
  while (ss >> n) {
   numInt[n]++;
  }
 }
 return 0;
}

I know I'm going about this wrong but I'm not sure how to properly do this.

1

There are 1 answers

0
Jerry Coffin On BEST ANSWER

I think I'd do something like this:

while (file >> ss) {
    if (isalpha((unsigned char)ss[0])
       names.push_back(ss);
    else {
       std::istringstream buf(ss);
       int n;

       while (buf >> n)
           numbers.push_back(n);
    }
}

This supports what you've asked for, but doesn't strictly enforce it. IOW, if you had something like:

Joe Blow
1 2 3
Jerry Coffin

...it would put "Joe Blow" and "Jerry Coffin" in the names and 1, 2 and 3 in the numbers.