反正有没有将filein重置为初始状态?

The*_* K. 1 c++ file-io stream fileinputstream

我试图用C++中的文本文件输入数据.文本文件采用以下格式:

4 15
3 516
25 52 etc.
Run Code Online (Sandbox Code Playgroud)

每行包含两个整数.我不知道文件中的行数,所以我可以绑定足够的内存,这就是我作为解决方法的方法:

ifstream filein;
filein.open("text.txt",ios::in);
int count=0;

while (!filein.eof())
    {
        count++;
        filein>>temporary;
    }
count=count/2; // This is the number of lines in the text file.
Run Code Online (Sandbox Code Playgroud)

我的问题是我无法想出一种重置方法

FILEIN

进入初始状态(到文件的开始,所以我实际上可以输入数据),而不是关闭输入流并再次打开它.还有其他办法吗?

Rob*_*obᵩ 5

我没有回答你问的问题,而是回答你没有提出的问题,即:

问:如果我不知道有多少行,我怎么能读入文件的所有行?

答:用一个std::vector<>.

如果您想要读入所有数字,无论配对如何:

// all code fragments untested. typos are possible
int i;
std::vector<int> all_of_the_values;
while(filein >> i)
    all_of_the_values.push_back(i);
Run Code Online (Sandbox Code Playgroud)

如果要读取所有数字,请将交替数字放入不同的数据结构中:

int i, j;
std::vector<int> first_values;
std::vector<int> second_values;
while(filein >> i >> j) {
    first_values.push_back(i);
    second_values.push_back(j);
Run Code Online (Sandbox Code Playgroud)

如果要读入所有数字,请将它们存储在某种数据结构中:

int i, j;
struct S {int i; int j;};
std::vector<S> values;
while(filein >> i >> j) {
    S s = {i, j};
    values.push_back(s);
}
Run Code Online (Sandbox Code Playgroud)

最后,如果您希望一次读取一行文件,保留每行的前两个数字,丢弃每行的其余部分,并将它们存储为用户定义的数据结构:

std::vector<MyClass> v;
std::string sline;
while(std::getline(filein, sline)) {
  std::istringstream isline(sline);
  int i, j;
  if(isline >> i >> j) {
    values.push_back(MyClass(i, j));
  }
}
Run Code Online (Sandbox Code Playgroud)


旁白:从不使用eof()good()循环条件.这样做几乎总会产生错误的代码,就像你的情况一样.相反,更喜欢在条件中调用输入函数,如上所述.