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?
How do you check if a char is a new line? Simply comparing to '\n' should solve your problem; depending on what you consider to be a newline character, you might also want to check for '\r' (carriage return).
In programming languages, such as C, Java, and Perl, the newline character is represented as a '\n' which is an escape sequence.
Open any text file and click on the pilcrow (¶) button. Notepad++ will show all of the characters with newline characters in either the CR and LF format. If it is a Windows EOL encoded file, the newline characters of CR LF will appear (\r\n). If the file is UNIX or Mac EOL encoded, then it will only show LF (\n).
"\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
.
You may want to try == '\n' instead of "\n".
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With