将行拆分为整数 [英] Splitting up lines into ints
本文介绍了将行拆分为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个从中读取的文件,它包含一堆行,每行都有不同数量的整数,我无法将其拆分为整数向量的向量.
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.
这是我当前的代码.
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.
我做错了什么?
推荐答案
问题在于您的 (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:
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;
}
这篇关于将行拆分为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文