Reputation:
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
Upvotes: 0
Views: 241
Reputation: 153899
The loop you've written is clearly wrong: you're testing eof()
before
failure, 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()
will
depend on what you try to read.) The correct pattern would be:
while ( i < size(str) && getline( readSWDS, str[i] ) ) {
if ( !str[i].empty() ) {
++ i;
}
Note that I've added a test for i
. As written, if your file contains
more 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, it
will 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 str
an
std::vector<std::string>
, and write the loop:
std::string line;
while ( std::getline( readSWDS, line ) ) {
if ( !line.empty() ) {
str.push_back(line);
}
}
This avoids having to define a fixed maximum number of lines.
Upvotes: 6