user3431800
user3431800

Reputation: 301

confusing behavior of detecting a blank line in a file using C++

Here is how my file data is arranged

10 12 19 21 3
11 18 25 2 9

1 3 1
0 5 0
2 1 2

when i use getline() and istringstream to line by line strip the file, i am concerning to detect the blank line in between these two data blocks. I need to detect it not to skip it.

so i wrote

while(getline(fp1,line)){
 if(line.empty()){
 cout<<"empty line"<<endl;
}

it does not work. And i think maybe the line is empty but contains with white space so I wrote

    while(getline(fp1,line)){
 if(line == "\n"){
 cout<<"empty line"<<endl;
}

not working. I even used line.find_first_not_of(' ') == std::string::npos as the condition, still no luck. Then i am thinking to print this blank space out to see what is in it.I printed all the length of my line, and i found the empty line has size 1. so then i wrote

if(line.length() == 1){
  cout<<hex<<  line;
  } 

i got a blank line back without anything.

I am confused. What am i suppose to do to detect this blank line? Please help!

Upvotes: 0

Views: 1181

Answers (2)

Paweł Stankowski
Paweł Stankowski

Reputation: 160

I think the additional character may be carriage return (\r) or another whitespace character. Note that std::hex does not affect strings or chars. To check what it is try:

cout<<hex<<  (int)line[0];

Upvotes: 0

Raindrop7
Raindrop7

Reputation: 3911

You can make a bool variable isBlanksetting it to true and inside the while loop after every line input you iterate over the line whether it is a blank or not:

std::ifstream in("test.txt");
std::string sLine;
bool isBlank = true;

while(std::getline(in, sLine)){
    isBlank = true;
    for(int i(0); i < sLine.length(); i++){
        if(!isspace(sLine[i])){
            isBlank = false;
            break;
        }
    }
    if(isBlank)
        std::cout << "Blank Line" << std:: endl;
    else
        std::cout << sLine << std::endl;
}

The output:

0 12 19 21 3
11 18 25 2 9
Blank Line
1 3 1
0 5 0
2 1 2

Upvotes: 1

Related Questions