简体   繁体   中英

Compare to newline windows C++

I have this simple code:

string isNewline(string text)
{   
    string toReturn;
    text == "\r\n" ? toReturn = "(newline)" : toReturn = text;
    return toReturn;
}

this function never returns a "(newline)" string, so I'm guessing that my comparison with newline character is wrong. How can I correct this?

PS. Windows function

There is nothing wrong with your isNewline function.

The problem is how you get the string to be passed to isNewline function.

I suspect you use something like getline(fin,aLine) to get the string like below?

while(getline(fin,aLine)){
   cout<<aLine<<endl; //aLine will never contain newline character because getline never save it
   cout<<isNewline(aLine)<<endl; // so this will never output "(newline)"
}

getline does not save the newline character into aLine

#include <string>
#include <iostream>
using namespace std;


string isNewline(string text)
{   
    string toReturn;
    text == "\r\n" ? toReturn = "(newline)" : toReturn = text;
    return toReturn;
}

int main() {
    cout << isNewline( "\r\n" ) << "\n";
    cout << isNewline( "zod" ) << "\n";
}

prints:

(newline)
zod

Note that you really want to be passing the string as a const::string &

Is not a good ideia to use assignment inside a conditional operator. But, there are anothers way to do the same thing. Look..

Use this:

string isNewline(string text)
{
    return (text == "\r\n" ? "(newline)" : text);
}

or

string isNewline(string text)
{
    string toReturn;
    toReturn = text == "\r\n" ? "(newline)" : text;
    return toReturn
}

I hope help you!

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