[英]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.这个 function 永远不会返回“(换行符)”字符串,所以我猜我与换行符的比较是错误的。 How can I correct this?我该如何纠正?
PS. PS。 Windows function Windows function
There is nothing wrong with your isNewline
function.您的isNewline
function 没有任何问题。
The problem is how you get the string to be passed to isNewline
function.问题是如何将字符串传递给isNewline
function。
I suspect you use something like getline(fin,aLine)
to get the string like below?我怀疑您使用getline(fin,aLine)
之类的方法来获取如下字符串?
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
getline
不会将换行符保存到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 &
请注意,您确实希望将字符串作为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!希望能帮到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.