在我的主代码中,我有一个操作,我想将字符串“ word [i]”的某个字符与拉丁字母“ b”进行比较。显然我尝试使用“ word [i] ==“ b”“,但是出现了错误。经过一些研究,我发现在C ++中,“ word [i] ==“ b”“比较两个指针。有人建议改用strcmp()。
所以我使用了strcmp(),但是仍然出现错误。有人可以向我解释为什么它不起作用吗?
最小工作示例:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
string test;
cin >> test;
if(strcmp(string[0], "a") == 0){
cout << "yes";
}
}
->
untitled.cpp: In function ‘int main()’:
untitled.cpp:8:18: error: expected primary-expression before ‘[’ token
8 | if(strcmp(string[0], "a") == 0){
| ^
Compilation failed.
答案 0 :(得分:1)
您的字符串未称为string
;它称为test
。
您通过提供类型名称而不是表达式来混淆编译器。
修复:
if(strcmp(test[0], "a") == 0){
// ^^^^
但是,这仍然是错误的。 test[0]
不是字符串;它是一个字符。
解决方案:
if (test[0] == 'a') {
// ^ ^
经过一番研究,我发现在C ++中“ word [i] ==” b“”与指针比较
对于C字符串,可以肯定,但是在C ++中,std::string
的定义是==
。
答案 1 :(得分:0)
很明显,我尝试使用“ word [i] ==” b“”,但出现了错误
表达式word[i]
(根据给出的程序,看来您的意思是test[i] == "b"
或更准确地说test[0] == "a"
)的类型为char
,而字符串文字为{{1} }的类型为"b"
。因此,由于类型不兼容,编译器会发出错误消息。
函数const char *
用于比较两个c字符串。如果要写个例子
strcmp
然后您将再次获得一个数组,因为表达式strcmp( word[i], "b" ) == 0
不是指向字符串的指针。它产生一个字符。
此外,在此if语句中
word]i]
您使用的是类型说明符if(strcmp(string[0], "a") == 0){
而不是对象。
您只需要写
std::string
在那里比较了if ( test[0] == 'a' ){
类型的两个对象:对象char
和字符文字test[0]
。
答案 2 :(得分:-1)
string[0]
无效,因为string
是类型名称。看来您的意思是test[0]
。
还要注意,strcmp(test[0], "a") == 0
不起作用,因为test[0]
是char
,而strcmp()
需要指向C样式字符串的指针(以{{1}结尾的字符序列})作为两个参数。
您要比较字符而不是字符串,因此应该为'\0'
或test[0] == 'a'
。