问题
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