简体   繁体   中英

New line character not appearing

Recently I wrote some code in which I need to identify a newline character. I believed using if(str == "") would not return true if the character was a \\n but I was wrong. If you run the following code with

steven 

bar

inside output.txt you will get no text at 2 which makes no sense because there should be a newline character there. Im pretty new to programming so here is the code.(It works if i if(str == '\\n') but im curious why the newline character isnt detected by if(str == "") .) Please clarify why C++ doesnt recognize the newline here is the code.

#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>

using namespace std;

int main()
{
    ifstream output;
    string line;
    int i = 1;
    output.open("output.txt");
    while(i <= 3)
    {
        getline(output, line, '\n');
        if(line == "")
        {
            cout << "no text found at "<< i << endl;
        }
        else
        {
            cout << "text at " << i << endl;
        }
        i++;
    }
    system("PAUSE");
}

According to cppreference :

getline [...] Extracts characters from input and appends them to str until one of the following occurs [...]

b) the next available input character is delim , [...] in which case the delimiter character is extracted from input , but is not appended to str .

So the string returned for your 2nd line is empty because the \\n delimiter is not appended to it.


You can confirm this behaviour by using a visible char as delimiter and checking the output :

output.open("output.txt");
getline(output, line, 'n');
cout << line << endl; // outputs "steve"

instead of steven , you get steve because the delimiter n is not appended.

The double quotation marks "" is empty string. New line character is different from empty string. Let's think in reverse, if you write

std::cout << "";

and

std::cout << std::endl;

First one will print nothing and cursor will stay at same line, while the second one will move the cursor to next line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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