[英]Compare to newline windows C++
我有这个简单的代码:
string isNewline(string text)
{
string toReturn;
text == "\r\n" ? toReturn = "(newline)" : toReturn = text;
return toReturn;
}
这个 function 永远不会返回“(换行符)”字符串,所以我猜我与换行符的比较是错误的。 我该如何纠正?
PS。 Windows function
您的isNewline
function 没有任何问题。
问题是如何将字符串传递给isNewline
function。
我怀疑您使用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
不会将换行符保存到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";
}
印刷:
(newline)
zod
请注意,您确实希望将字符串作为const::string &
在条件运算符中使用赋值不是一个好主意。 但是,还有其他方法可以做同样的事情。 看..
用这个:
string isNewline(string text)
{
return (text == "\r\n" ? "(newline)" : text);
}
或者
string isNewline(string text)
{
string toReturn;
toReturn = text == "\r\n" ? "(newline)" : text;
return toReturn
}
希望能帮到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.