How to look if a char is equal to a new line
Solution 1
"\n"
is a const char[2]
. Use '\n'
instead.
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).
Also notice the use of size_t
instead of the conversion of inData.length()
to int
.
Solution 2
You may want to try == '\n' instead of "\n".
Solution 3
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
Laurence
Updated on February 15, 2020Comments
-
Laurence about 4 years
I have a string, the string contains for example "Hello\nThis is a test.\n".
I want to split the whole string on every \n in the string. I made this code already:
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)
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?