我想从文本文件中读取图形邻接信息,并将其存储到向量中。
结尾的整数
例如,
First line:
0 1 4
Second line:
1 0 4 3 2
Thrid line:
2 1 3
Fourth line:
3 1 2 4
Fifth line:
4 0 1 3
如果我使用getline()一次读取一行,我如何解析该行(因为每行都有可变数量的整数)?
有什么建议吗?
发布于 2011-11-14 11:03:03
标准的在线阅读习惯用法:
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
std::ifstream infile("thefile.txt");
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int n;
std::vector<int> v;
while (iss >> n)
{
v.push_back(n);
}
// do something useful with v
}
下面是一个使用for
循环的单行版本。我们需要一个辅助结构(致谢@Luc Danton!)这与std::move
正好相反。
namespace std
{
template <typename T> T & stay(T && t) { return t; }
}
int main()
{
std::vector<std::vector<int>> vv;
for (std::string line;
std::getline(std::cin, line);
vv.push_back(std::vector<int>(std::istream_iterator<int>(std::stay(std::istringstream(line))),
std::istream_iterator<int>())
)
) { }
std::cout << vv << std::endl;
}
发布于 2011-11-14 11:02:26
首先使用std::getline
函数读取一行,然后使用std::stringstream
从该行读取整数,如下所示:
std::ifstream file("input.txt");
std::vector<std::vector<int>> vv;
std::string line;
while(std::getline(file, line))
{
std::stringstream ss(line);
int i;
std::vector<int> v;
while( ss >> i )
v.push_back(i);
vv.push_back(v);
}
你也可以把循环体写成:
while(std::getline(file, line))
{
std::stringstream ss(line);
std::istream_iterator<int> begin(ss), end;
std::vector<int> v(begin, end);
vv.push_back(v);
}
这个看起来更短,也更好。或合并-最后两行:
while(std::getline(file, line))
{
std::stringstream ss(line);
std::istream_iterator<int> begin(ss), end;
vv.push_back(std::vector<int>(begin, end));
}
现在不要让它变短,因为它会看起来很丑陋。
https://stackoverflow.com/questions/8116808
复制相似问题