【问题标题】:Reading txt multiple times多次读取txt
【发布时间】:2013-03-27 18:34:00
【问题描述】:

我有一个使用 text_file 存储大量数字的程序。 当我必须加载这些数字时,我必须一次加载 2500 个数字。 我有一个while循环来一次又一次地加载它......

现在,我猜这个问题出现在 while 循环中。

ifstream mfile("abc.txt", ifstream::out);
if(mfile.is_open())
{
    getline(mfile, b);
    char* ch = new char[b.length() + 1];
    strcpy(ch, b.c_str());
    result = atof(strtok (ch,";"));
    while(i<125)
    {
        cout<< strtok (NULL,";")<<" ";
        i++;
    }
    i=0;
}
else
{
    cout<<"probleem";
}
mfile.close();

这是问题所在的更复杂代码的简短示例。

注意这段代码必须在while循环中。

但是它只运行一次代码,可能是因为mfile不能多次使用。 当我想多次读取文件时,有必要从上一次读取的末尾开始读取。

【问题讨论】:

  • 存储您离开并从那里继续的地方?
  • 是的,但我仍然必须使用 while 循环,因为我必须继续
  • 我不明白这个问题。为什么不直接在while循环外部打开和关闭文件?在循环内部,第一个getline() 将读取第一行,第二个将读取第二行,依此类推。 (另外,strtok(NULL,';') 应该完成什么?)

标签: c++ text-files iostream fstream


【解决方案1】:
  ifstream mfile("abc.txt", ifstream::out);  // why out ??

--->

  ifstream mfile("abc.txt");
  if(mfile.is_open())
 {  while(getline(mfile, b))
    {   char* ch = new char[b.length() + 1];
        strcpy(ch, b.c_str());
        result = atof(strtok (ch,";"));
        while(i<125)
        {    cout<< strtok (NULL,";")<<" ";
          i++;
        }
        i=0;
    }
 }
 else     {     cout<<"probleem";      }
 mfile.close();

您也可以使用streampos tellg();seekg(pos) 的组合

编辑:

istream&amp; getline (istream&amp; is, string&amp; str);

将返回mfile,其中while(mfile) 将被隐式转换为bool,因此有效地迭代直到无法再读取任何字符串,通常在文件末尾。

【讨论】:

  • 谢谢,它认为它会起作用,但是 while(getline(...)) 是什么意思?读到文件末尾?
猜你喜欢
  • 2017-05-30
  • 1970-01-01
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2021-12-28
  • 2019-08-04
相关资源
最近更新 更多