C++ – Splitting up lines into ints

cinputstdstdin

I have a file that I read from, it contains a bunch of lines each with a different number of integers, I'm having trouble splitting it up into a vector of a vector of ints.

This is my current code.

std::vector<int> read_line()
{
    std::vector<int> ints;
    int extract_int;
    while((const char*)std::cin.peek() != "\n" && std::cin.peek() != -1)
    {
        std::cin >> extract_int;
        ints.push_back(extract_int);
    }
    return ints;
}
std::vector<std::vector<int> > read_lines()
{
    freopen("D:\\test.txt", "r", stdin);
    freopen("D:\\test2.txt", "w", stdout);
    std::vector<std::vector<int> > lines;
    while(!std::cin.eof())
    {
        lines.push_back(read_line());
    }
    return lines;
}

The problem is that all of the ints are being read as a single line.

What am I doing wrong?

Best Answer

You may want to use getline() to read in a line, and then a string stream out of that line instead of trying to treat the entire file as a single stream.

Related Topic