Dealing with tabs with ifstream and reading an arbitrary number of values into a vector


New Member
I'm basically working with fragments of a text file like this:
    Jane Doe
    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?


Thành viên BQT
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.
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);

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

for(const auto& i : v){
    std::cout << i << " ";