[英]Using getline and istringstream to read from file is producing zeroes
我有一个看起来像这样的文本文件:
6
1 2 3 4 5 6
1 2
1 4
1 5
2 3
2 5
2 6
3 4
3 6
4 5
5 6
我使用以下内容将文件的行读入我的变量和数组:
//Read first line
if( std::getline(in, line))
{
std::istringstream iss(line);
while( iss >> a);
}
// read second line
int i = 0;
if( std::getline(in, line) )
{
std::istringstream iss(line);
while( iss >> b[i] )
{
++i;
}
}
// read rest of file matrix
int x = 0;
while( !in.eof())
{
if( std::getline(in, line))
{
std::istringstream iss1(line);
while( iss1 >> c[x])
{
++x;
}
}
}
在上面的代码中, a
是一个int, b
和c
是一个int数组, in
是一个istream运算符, line
是一个std::string
。 但是当我std::cout
变量和数组时,它似乎工作正常,我得到以下信息:
6
1,2,3,4,5,6
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
由于某种原因,数组c
似乎充满了全零而不是文件中的数据。 这对我来说很奇怪,因为我以完全相同的方式阅读前两行,而且它们似乎读得很好。 有任何想法吗?
我终于想通了,我想将它发布在这里供将来的人们使用。 我最终实现了以下功能,并且可以正常工作。
// declare the variables to be used
int a, b, c, d, e;
std::string line;
// open file for reading
in.open(file);
in >> a;
std::cout << a << '\n';
for(int i=0; i<a; ++i)
in >> b
in >> c;
for(int i = 0; i < c; ++i)
{
in >> d >> e;
// push to vector here
}
in.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.