用C ++ ifstream从文本文件中读取整数
我想从文本文件中读取graphics邻接信息并将其存储到一个向量中。
- 
该文件具有任意数量的行 
- 
每行有任意数量的以'\ 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()一次读取一行,我该如何parsing这一行(因为每一行都有可变整数)?
有什么build议么?
标准阅读习语成语:
 #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; } 
 首先使用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)); } 
现在不要缩短,因为它看起来很丑。