Reputation: 99
I'm actually trying to understand how does the getline()
function works! But I'm facing difficulties to test if a line is empty or not!
Here is my code:
ifstream fichier("upload.txt",ios::binary);
string ligne;
while(getline(fichier,ligne))
{
cout<<ligne<<endl;
if(ligne=="")
cout<<"line below is empty"<<endl;
}
But, the if-condition seems to be not working :((
Upvotes: 0
Views: 293
Reputation: 598384
On Windows, a line break is normally CRLF (0x0D 0x0A
). std::getline()
will read until it encounters the LF and discard it from the returned std::string
. If the std::ifstream
is opened in text mode (the default mode), platform line breaks are normalized to LF and a leading CR will also be discarded. But, if opened in binary mode, the CR will not be discarded. So you will have to check for that:
ifstream fichier("upload.txt", ios::binary);
string ligne;
while (getline(fichier, ligne)) {
if (ligne.empty() || ligne == "\r") {
cout << "line is empty" << endl;
} else {
cout << ligne << endl;
}
}
Otherwise, don't use binary mode for text files:
ifstream fichier("upload.txt");
string ligne;
while (getline(fichier, ligne)) {
if (ligne.empty()) {
cout << "line is empty" << endl;
} else {
cout << ligne << endl;
}
}
Upvotes: 2
Reputation: 1221
Your problem is opening file in binary. Other than that, you should do few things :
Close file
ifstream fichier("upload.txt", std::ifstream::in ); //File opened for reading.
string ligne;
//Always Check if file is properly opened.
if (fichier.is_open() )
{
while(getline(fichier,ligne))
{
cout<<ligne<<endl;
if(ligne.empty() || str.find_first_not_of(' ') == std::string::npos)
cout<<"line below is empty"<<endl;
}
fichier.close();
}
else
{
// show message:
std::cout << "Error opening file";
}
Upvotes: 0