How to see if char matches a new line

I have a line, the line contains, for example, "Hello \ nThis is a test. \ N".

I want to split the whole line on every \ n in the line. I already made this code:

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 agree with this, I get the error message: (\ 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 see if char matches the "new line". How can i do this?

+4
source share
3 answers

"\n" is a const char[2] . Use '\n' instead.

In general, your code will not even compile.

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 vector from your code because you obviously don't want to use it (you tried to initialize vector<string> from const char[] , which will not work).

Also note the use of size_t instead of converting inData.length() to int .

+13
source

You can try == '\ n' instead of "\ n".

+4
source

Your test expression is also incorrect, it 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 must create a function that takes a string and returns the vector of the string containing the stranded strings. I think,

+1
source

Source: https://habr.com/ru/post/1396440/


All Articles