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?
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.
The problem is your (const char *)std::cin.peek() != "\n"
cast. casts are evil; try to avoid using them. The following code works:
std::vector<int> read_line()
{
std::vector<int> ints;
int extract_int;
while(std::cin.peek() != '\n' && std::cin.peek() != -1)
{
std::cin >> extract_int;
ints.push_back(extract_int);
}
std::cin.ignore(); // You need this to discard the \n
return ints;
}
Read a single line into a vector with
std::vector<int> read_line()
{
std::vector<int> ints;
std::string line;
std::getline(std::cin, line);
int i;
std::stringstream ss(line);
while (ss >> i)
ints.push_back(i);
return ints;
}
and then all vectors with
std::vector< std::vector<int> > read_lines()
{
std::vector< std::vector<int> > lines;
while (std::cin) {
std::vector<int> line = read_line();
if (std::cin)
lines.push_back(line);
}
return lines;
}
Then print the result with
template<class T>
struct print : public std::unary_function<T,void>
{
print(std::ostream &out) : os(out) {}
void operator() (T x) { os << '[' << x << ']'; }
std::ostream &os;
};
void print_vector(const std::vector<int> &v)
{
std::for_each(v.begin(), v.end(), print<int>(std::cout));
std::cout << '\n';
}
int main()
{
std::vector< std::vector<int> > lines = read_lines();
std::for_each(lines.begin(), lines.end(), print_vector);
return 0;
}
For example:
$ cat input 1 2 3 4 5 6 7 8 9 10 $ ./try.exe <input [1][2][3][4] [5][6] [7][8][9] [10]
精彩评论