1

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...

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.

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

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
abcdef
  • 236
  • 1
  • 5
  • 17
  • Store where you left off and continue from there? – DiegoNolan Mar 27 '13 at 18:38
  • Yeah but than I still have to use a while loop because I have to continue – abcdef Mar 27 '13 at 18:48
  • I don't understand the problem. Why don't you just open and close the file _outside_ the while-loop? Inside the loop, the first `getline()` will read the first line, the second one will read the second line, and so on. (On a separate note, what is `strtok(NULL,';')` supposed to accomplish?) – jogojapan Mar 29 '13 at 02:40

1 Answers1

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

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

EDIT:

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

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.

qPCR4vir
  • 3,521
  • 1
  • 22
  • 32
  • Thanks, it think it will work, but what does while(getline(...)) mean? Read until end of the file? – abcdef Mar 27 '13 at 18:58