如何查看char是否等於新行

[英]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".

我有一個字符串,該字符串包含例如“Hello \ n這是一個測試。\ 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 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?

問題是我無法查看char是否等於“new line”。我怎樣才能做到這一點?

3 个解决方案

#1


14  

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

我從代碼中刪除了向量,因為你顯然不想使用它(你試圖從const char []初始化vector ,這將無法工作)。

Also notice the use of size_t instead of the conversion of inData.length() to int.

另請注意使用size_t而不是將inData.length()轉換為int。

#2


4  

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

您可能想嘗試=='\ n'而不是“\ n”。

#3


1  

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

你應該創建一個帶字符串的函數,並返回包含spitted行的字符串向量


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/02/14/72f73a4525ed9af78acdd3b940d5f266.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com