C++ 如何查看字符是否等于新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9281009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to look if a char is equal to a new line
提问by Laurence
I have a string, the string contains for example "Hello\nThis is a test.\n".
我有一个字符串,该字符串包含例如“Hello\nThis is a test.\n”。
I want to split the whole string on every \n in the string. I made this code already:
我想在字符串中的每个 \n 上拆分整个字符串。我已经做了这个代码:
vector<string> inData = "Hello\nThis is a test.\n";
for ( int i = 0; i < (int)inData.length(); i++ )
{
if(inData.at(i) == "\n")
{
}
}
But when I complite this, then I get an error: (\n as a string)
但是当我完成这个时,我得到一个错误:(\n 作为一个字符串)
binary '==' : no operator found which takes a left-hand operand of type 'char' (or there is no acceptable conversion)
(above code)
(以上代码)
'==' : no conversion from 'const char *' to 'int'
'==' : 'int' differs in levels of indirection from 'const char [2]'
The problem is that I can't look if a char is equal to "new line". How can I do this?
问题是我看不到一个字符是否等于“新行”。我怎样才能做到这一点?
回答by netcoder
"\n"
is a const char[2]
. Use '\n'
instead.
"\n"
是一个const char[2]
。使用'\n'
来代替。
And actually, your code won't even compile anyway.
实际上,您的代码无论如何都无法编译。
You probably meant:
你可能的意思是:
string inData = "Hello\nThis is a test.\n";
for ( size_t i = 0; i < inData.length(); i++ )
{
if(inData.at(i) == '\n')
{
}
}
I removed the vector
from your code because you apparently don't want to use that (you were trying to initialize a vector<string>
from a const char[]
, which will not work).
我vector
从您的代码中删除了,因为您显然不想使用它(您试图vector<string>
从 a初始化a const char[]
,但这是行不通的)。
Also notice the use of size_t
instead of the conversion of inData.length()
to int
.
还要注意使用 ofsize_t
而不是inData.length()
to的转换int
。
回答by David
You may want to try == '\n' instead of "\n".
您可能想尝试 == '\n' 而不是 "\n"。
回答by Mr.Anubis
your test expression is also wrong, That should be
你的测试表达式也错了,应该是
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')
{
}
}
you should create a function which takes a string , and return vector of string containing spitted lines I think
你应该创建一个函数,它接受一个字符串,并返回包含我认为的吐线的字符串向量