简体   繁体   English

使用C ++在文件中检测空白行的混乱行为

[英]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. 当我使用getline()和istringstream逐行删除文件时,我正在考虑检测这两个数据块之间的空白行。 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. 我什至使用line.find_first_not_of('')== std :: string :: npos作为条件,仍然没有运气。 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 然后我想将这个空白打印出来以查看其中的内容。我打印了所有行的长度,发现空行的大小为1。于是我写了

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! 请帮忙!

You can make a bool variable isBlank setting it to true and inside the while loop after every line input you iterate over the line whether it is a blank or not: 您可以将一个bool变量isBlank设置为true,并在您遍历该行的每行输入之后的while循环内迭代该行是否为空:

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

I think the additional character may be carriage return (\\r) or another whitespace character. 我认为其他字符可能是回车符(\\ r)或其他空格字符。 Note that std::hex does not affect strings or chars. 请注意,std :: hex不会影响字符串或字符。 To check what it is try: 要检查它是什么,请尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM