1

I'm basically working with fragments of a text file like this:

6
    Jane Doe
    1942
    90089
    3 1 5 12

There are tabs on lines 2-5. I'm trying to hold each of the values in an appropriate variable and I would like to have the numbers on the bottom line stored in a vector called friends, e.g. <3, 1, 5, 12>. There can be an arbitrary number of numbers on the last line. I also don't know if I'm missing anything with how ifstream processes tabs.

Here's what I have so far:

int id;
ifile >> id;
string name;
getline(ifile, name);
int year;
ifile >> year;
int zip;
ifile >> zip;
vector<int> friends;
// Not sure how to read in the vector if it has an arbitary length
// Use getline and somehow read everything in from the string?

How would I approach the vector? While loop?

  • 1
    "Use getline and somehow read everything in from the string?" Yes, you could do that and construct a `std::stringstream` from the string. Read from the stringstream until extraction fails. – Swordfish Nov 08 '18 at 05:04
  • 2
    [Option two in the linked answer can be used as inspiration.](https://stackoverflow.com/a/7868998/4581301) – user4581301 Nov 08 '18 at 05:07

1 Answers1

0

I think that reading each field by std::getline makes the code clear and readable. On the last line, reading a line using std::getline and std::stringstream, we can read arbitrary number of numbers as follows. This post would be helpful.

std::string buffer;

std::getline(ifile, buffer);
const int id = std::stoi(buffer);

std::string name;
std::getline(ifile, name);
name.erase(std::remove(name.begin(), name.end(), '\t'), name.end());

std::getline(ifile, buffer);
const int year = std::stoi(buffer);

std::getline(ifile, buffer);
const int zip = std::stoi(buffer);

std::getline(ifile, buffer);
std::stringstream ss(buffer);
std::istream_iterator<int> begin(ss), end; //defaulted end-of-stream iterator.
const std::vector<int> v(begin, end);

std::cout
    << "id:" << id << std::endl
    << "name:" << name << std::endl
    << "year:" << year << std::endl
    << "zip:" << zip << std::endl;

for(const auto& i : v){
    std::cout << i << " ";
}
Hiroki
  • 2,780
  • 3
  • 12
  • 26