[英]Read integers from a text file with 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()讀取一行,我該如何解析該行(因為每行有可變數量的整數)?
有什么建議?
標准讀書成語:
#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));
}
現在不要縮短它,因為它看起來很難看。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.