多次读txt [英] Reading txt multiple times

查看:133
本文介绍了多次读txt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a program which uses a text_file to store lots of numbers. When I have to load those numbers I have to load it with 2500 numbers a time. I have a while loop to load it again and again and again...

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

Now, the problem occurs in the while loop I guess.

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();

这是一个简单而简单的例子,代表更复杂的问题。

this is a short and simply example of the more complicated code which is the problem.

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

Notice that this piece of code must be in a while loop.

但是它只运行一次代码, code> mfile 不能使用多次。
当我要多次读取文件时,需要从上一次读取结束时开始读取。

But it only runs the code once, maybe because mfile can't be used several times. When I want to read the file multiple times it is necessary that it begins to read from the end of the previous reading.

推荐答案

  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 / code>

You also may esa a combination of streampos tellg(); and seekg(pos)

编辑:

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

将返回 mfile ,其中 while(mfile)将被隐式转换为 bool ,从而有效迭代,直到它是不可能读取任何字符串更多,tipicaly由文件结束。

will return mfile, with inside the while(mfile) will be implicitaly converted into a bool, thus efectively iterating until it is not posible to read any string more, tipicaly by the end of file.

这篇关于多次读txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆