[英]Error working with C-Strings
I have a simple example from a C++ textbook that defines a C-String and then loops to replace all the elements that are not the \\0 character with X. 我有一个来自C ++教科书的简单示例,该示例定义了C-String,然后循环使用X替换所有非\\ 0字符的元素。
char ourString[5] = "Hi";
int index = 0;
while(ourString[index] != "\0")
{
ourString[index] = "X";
index++;
}
cout << ourString[] << endl;
However when I compile and run I get the following error: 但是,当我编译并运行时,出现以下错误:
C:\Users\Ben\Dropbox\Learning Programming\C++\Strings\Strings.cpp||In function 'int main()':|
C:\Users\Ben\Dropbox\Learning Programming\C++\Strings\Strings.cpp|17|error: ISO C++ forbids comparison between pointer and integer [-fpermissive]|
C:\Users\Ben\Dropbox\Learning Programming\C++\Strings\Strings.cpp|19|error: invalid conversion from 'const char*' to 'char' [-fpermissive]|
C:\Users\Ben\Dropbox\Learning Programming\C++\Strings\Strings.cpp|23|error: expected primary-expression before ']' token|
||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===|
I don't see the problem why it's not letting me (as far as I can understand the error) compare the elements which are characters, to the character \\0. 我看不出为什么它不能让我(据我所能理解的错误)将字符元素与字符\\ 0进行比较的问题。 I don't think I am trying to compare a pointer to an integer... 我不认为我正在尝试将指针与整数进行比较...
You need use single quotes in two places. 您需要在两个地方使用单引号。
while(ourString[index] != '\0')
{
ourString[index] = 'X';
index++;
}
Since you have double quotes, it's considered as string literal. 由于您有双引号,因此将其视为字符串文字。
Change "\\0"
to '\\0'
. 将"\\0"
更改为'\\0'
。 The first is a string literal that decays to a pointer, and as compiler told you, you're not allowed to compare pointers to integers. 第一个是会分解为指针的字符串文字,并且正如编译器告诉您的那样,不允许将指针与整数进行比较。 The latter is a plain old character literal. 后者是普通的旧字符文字。
The same goes for ourString[index] = "X";
ourString[index] = "X";
, change "X"
to 'X'
. ,将"X"
更改为'X'
。
And the last line should be cout << ourString << endl;
最后一行应该是cout << ourString << endl;
; ;
You're confusing characters with strings. 您将字符与字符串混淆。 You need to switch the "\\0"
to '\\0'
and "X"
to 'X'
. 您需要将开关"\\0"
到'\\0'
和"X"
到'X'
。 Also you should not use []
on the cout
statement - combining these gives: 另外,您不应该在cout
语句上使用[]
-将这些结合起来可以得出:
char ourString[5] = "Hi";
int index = 0;
while(ourString[index] != '\0')
{
ourString[index] = 'X';
index++;
}
cout << ourString << endl;
Note that you can write this in a neater form: 请注意,您可以使用整洁的形式编写此代码:
for( char* c = ourString; *c ; ++c) // *c is the same as *c!='\0'
{
*c='X';
}
cout << ourString << endl;
replace while(ourString[index] != "\\0")
with 与
while(ourString[index] != '\\0')
Replace double ticks with single ones. 用单勾号代替双勾号。
you used a null operator, it is not used with double quotation "" it always used with single quotation '\\0' 您使用了null运算符,它不与双引号“”一起使用,而总是与单引号'\\ 0'一起使用
try this,, 尝试这个,,
while(ourString[index] != '\0')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.