It’s been a while since I’ve worked with File I/O in C++ (and just C++ in general) but I recently decided to use it to make a small console project for a friend.
My issue is that I’m having some issues with a string array and File I/O (I’m not sure which is causing the problem). My code is as follows (ReadPSWDS is an ifstream):
int i = 0;
string str[200];
ReadPSWDS.clear();
ReadPSWDS.open("myPasswords.DoNotOpen");
if(ReadPSWDS.is_open())
{
while(!ReadPSWDS.eof())
{
getline(ReadPSWDS, str[i]); //Store the line
if(str[i].length()<1 || str[i] == "")
{
//Ignore the line if it's nothing
}
else
{
i++; //Move onto the next 'cell' in the array
}
}
}
ReadPSWDS.close();
My issue is that on testing this out, the string array would appear to be empty (and on writing all those lines to a file, the file is empty as expected).
Why is the string array empty and not filled with the appropriate lines of the text file?
Regards,
Joe
The loop you’ve written is clearly wrong: you’re testing
eof()beforefailure, and you’re not testing for failure after the
getline. C++I/O isn’t predictive. (I can’t be, since whether you’re at
eof()willdepend on what you try to read.) The correct pattern would be:
Note that I’ve added a test for
i. As written, if your file containsmore than 200 lines, you’re in deep trouble.
I’m not sure that this is your problem, however; the loop as you’ve
written it will normally only cause problems on the last line.
(Typically, if the last line ends with a
'\n', and is not empty, itwill appear twice in your array.) Unless, of course, your file does
contain more than 200 lines.
I might add that an even more typical idiom would be to make
stranstd::vector<std::string>, and write the loop:This avoids having to define a fixed maximum number of lines.