使用C ++ ifstream从文本文件读取整数

我想从文本文件中读取图邻接信息并将其存储到向量中。


该文件具有任意行


每行都有任意数量的以'\ n'结尾的整数


例如,


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()一次读取一行,该如何解析该行(因为每一行都有可变数量的整数)?


有什么建议么?


慕码人8056858
浏览 1736回答 3
3回答

一只萌萌小番薯

首先使用std::getline函数读取一行,然后使用std::stringstream来从该行读取整数,如下所示:std::ifstream file("input.txt");std::vector<std::vector<int>> vv;std::string line;while(std::getline(file, line)){&nbsp; &nbsp; std::stringstream ss(line);&nbsp; &nbsp; int i;&nbsp; &nbsp; std::vector<int> v;&nbsp; &nbsp; while( ss >> i )&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;v.push_back(i);&nbsp; &nbsp; vv.push_back(v);}您还可以将循环体编写为:while(std::getline(file, line)){&nbsp; &nbsp; std::stringstream ss(line);&nbsp; &nbsp; std::istream_iterator<int> begin(ss), end;&nbsp; &nbsp; std::vector<int> v(begin, end);&nbsp; &nbsp; vv.push_back(v);}这看起来更短,更好。或合并-最后两行:while(std::getline(file, line)){&nbsp; &nbsp; std::stringstream ss(line);&nbsp; &nbsp; std::istream_iterator<int> begin(ss), end;&nbsp; &nbsp; vv.push_back(std::vector<int>(begin, end));}现在不要将其缩短,因为它看起来很丑。
打开App,查看更多内容
随时随地看视频慕课网APP