将行拆分为整数
我有一个我读取的文件,它包含一堆行,每行都有不同数量的整数,我无法将其拆分为整数向量的向量。
这是我当前的代码。
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;
}
问题是所有的整数都被作为一行读取。
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能需要使用
getline()
来阅读在一行中,然后是该行中的 字符串流 而不是尝试处理整个文件作为单个流。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.问题是你的
(const char *)std::cin.peek() != "\n"
转换。 强制转换是邪恶的;尽量避免使用它们。以下代码有效:The problem is your
(const char *)std::cin.peek() != "\n"
cast. casts are evil; try to avoid using them. The following code works:将单行读入向量,
然后将所有向量读入,
然后打印结果,
例如:
Read a single line into a vector with
and then all vectors with
Then print the result with
For example: