Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to look if a char is equal to a new line

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?

like image 694
Laurence Avatar asked Feb 14 '12 17:02

Laurence


People also ask

How do you check if a char is a newline?

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).

Is newline a character in C?

In programming languages, such as C, Java, and Perl, the newline character is represented as a '\n' which is an escape sequence.

How do you show a new line character in Notepad ++?

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).


3 Answers

"\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.

like image 175
netcoder Avatar answered Oct 06 '22 02:10

netcoder


You may want to try == '\n' instead of "\n".

like image 37
David Avatar answered Oct 06 '22 02:10

David


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

like image 45
Mr.Anubis Avatar answered Oct 06 '22 02:10

Mr.Anubis