【问题标题】:Compare to newline windows C++与换行窗口 C++ 比较
【发布时间】:2011-05-28 15:56:47
【问题描述】:

我有这个简单的代码:

string isNewline(string text)
{   
    string toReturn;
    text == "\r\n" ? toReturn = "(newline)" : toReturn = text;
    return toReturn;
}

这个函数从不返回“(newline)”字符串,所以我猜测我与换行符的比较是错误的。我该如何纠正这个问题?

PS。窗口功能

【问题讨论】:

  • 你必须展示它是如何被调用的。
  • 比较之前的修剪怎么样? remove(text.begin(), text.end(), ' '); // #include <algorithm>
  • text == "\r\n" ? toReturn = "(newline)" : toReturn = text; 有效但很奇怪。更喜欢toReturn = (text == "\r\n" ? "(newline)" : text);(你也可以直接return!)

标签: c++ compare newline


【解决方案1】:

你的isNewline函数没有问题。

问题在于如何将字符串传递给isNewline 函数。

我怀疑你使用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

【讨论】:

  • 是的...我的问题就在这里。这个答案帮助我理解了它。谢谢!
【解决方案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";
}

打印:

(newline)
zod

请注意,您确实希望将字符串作为const::string &amp; 传递

【讨论】:

    【解决方案3】:

    在条件运算符中使用赋值不是一个好主意。 但是,还有其他方法可以做同样的事情。看..

    使用这个:

    string isNewline(string text)
    {
        return (text == "\r\n" ? "(newline)" : text);
    }
    

    string isNewline(string text)
    {
        string toReturn;
        toReturn = text == "\r\n" ? "(newline)" : text;
        return toReturn
    }
    

    希望能帮到你!

    【讨论】:

    • 该行将返回三元运算符的结果,即,("newline") ou text,并且都是字符串类型!
    • 那么,这些功能和 OP 发布的那一个有什么区别呢?它们都是相同的,但以不同的方式编写。
    • @Jonatas:Yes you can。赋值是一个有效的表达式;考虑if (a = 2) {..}但是,您的替代建议在代码风格方面更胜一筹。
    • 是条件运算符。是的,你可以。
    • @Neil:在更广泛的术语意义上,它是一种称为“条件运算符”的三元运算符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2021-11-16
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多