问题
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.
回答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.
来源:https://stackoverflow.com/questions/15666738/reading-txt-multiple-times