[英]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.