【问题标题】:How to look if a char is equal to a new line如何查看 char 是否等于新行
【发布时间】:2012-03-06 01:32:34
【问题描述】:

我有一个字符串,该字符串包含例如“Hello\nThis is a test.\n”。

我想在字符串中的每个 \n 上拆分整个字符串。我已经编写了这段代码:

vector<string> inData = "Hello\nThis is a test.\n";

for ( int i = 0; i < (int)inData.length(); i++ )
{
    if(inData.at(i) == "\n")
    {
    }
}

但是当我编译这个时,我得到一个错误: (\n 作为字符串)

binary '==' : no operator found which takes a left-hand operand of type 'char' (or there is no acceptable conversion)

(以上代码)

'==' : no conversion from 'const char *' to 'int'

'==' : 'int' differs in levels of indirection from 'const char [2]'

问题是我无法查看 char 是否等于“新行”。我该怎么做?

【问题讨论】:

  • 你确定你的意思是成为vector&lt;string&gt;

标签: c++ windows char newline equals


【解决方案1】:

"\n"const char[2]。请改用'\n'

实际上,您的代码甚至都无法编译。

你的意思可能是:

string inData = "Hello\nThis is a test.\n";

for ( size_t i = 0; i < inData.length(); i++ )
{
    if(inData.at(i) == '\n')
    {
    }
}

我从您的代码中删除了vector,因为您显然不想使用它(您试图从const char[] 初始化vector&lt;string&gt;,这是行不通的)。

还要注意使用size_t 而不是将inData.length() 转换为int

【讨论】:

  • "\n" 肯定不是char const*;这是char const[2]
【解决方案2】:

你的测试表达也错了,应该是

vector<string> inData (1,"Hello\nThis is a test.\n");

for ( int i = 0; i < (int)(inData[0].length()); i++ )
{
    if(inData.at(i) == '\n')
    {
    }
}

你应该创建一个函数,它接受一个字符串,并返回我认为包含吐线的字符串向量

【讨论】:

  • inData[0] 并不总是保存使用。在这种情况下,它是可摆的。 inData 是一个向量,为什么不用 at 呢?
  • @lauw 我只是让他知道出了什么问题,这取决于他在做什么。
【解决方案3】:

您可能想尝试 == '\n' 而不是 "\n"。

【讨论】:

    猜你喜欢
    • 2018-08-31
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多