Compare to newline windows C++

只愿长相守 提交于 2020-02-25 08:07:13

问题


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


回答1:


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




回答2:


#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 &




回答3:


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!



来源:https://stackoverflow.com/questions/6162731/compare-to-newline-windows-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!