使用 C++ ifstream 从文本文件中读取整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8116808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read integers from a text file with C++ ifstream
提问by itnovice
I want to read graph adjacency information from a text file and store it into a vector.
我想从文本文件中读取图形邻接信息并将其存储到向量中。
the file has arbitrary number of lines
each line has arbitrary number of integers ended with '\n'
该文件具有任意数量的行
每行有任意数量的以 '\n' 结尾的整数
for example,
例如,
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
If I use getline() to read one line at a time, how do I parse the line (as each line has variable number of integers)?
如果我使用 getline() 一次读取一行,我该如何解析该行(因为每行都有可变数量的整数)?
Any suggestions?
有什么建议?
采纳答案by Kerrek SB
The standard line reading idiom:
标准行阅读成语:
#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
}
Here's a one-line version using a for
loop. We need an auxiliary construction (credits to @Luc Danton!) that does the opposite of std::move
:
这是使用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;
}
回答by Nawaz
First read a line using std::getline
function, then use std::stringstream
to read the integers from the line as:
首先使用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);
}
You can also write the loop-body as:
您还可以将循环体写为:
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);
}
This looks shorter, and better. Or merge-the last two lines:
这看起来更短,更好。或合并-最后两行:
while(std::getline(file, line))
{
std::stringstream ss(line);
std::istream_iterator<int> begin(ss), end;
vv.push_back(std::vector<int>(begin, end));
}
Now don't make it shorter, as it would look ugly.
现在不要让它变短,因为它看起来很难看。