【问题标题】:C: Failed to compare character [duplicate]C:无法比较字符[重复]
【发布时间】:2021-01-08 01:46:00
【问题描述】:

我有如下的 C 代码。我有abcd 作为输入,我想要的输出是aBcd

但是在line1[i] == "b" 的行,我得到一个错误,说我正在比较指针和整数...为什么“b”是一个整数?

我尝试了"b" == line1[i],但没有成功。我怎样才能把它修好?谢谢

#include<stdio.h>
#include<string.h>

int main(){

  char line1[10]="abcd";
  char line2[10];
    strcpy(line2, line1);

  int i;
  for (i = 0; i < 10; ++i)
  {
    if(line1[i] == "b"){
      line2[i] = "B";
    }
  }

  printf("%s",line2);
  return 0;
}

【问题讨论】:

  • 双引号字符串,你单引号字符......

标签: arrays c string char


【解决方案1】:

这是不正确的:

 if (line1[i] == "b")

你是在比较字符,而不是字符串,所以它应该是:

if (line1[i] == 'b')

你得到的错误信息:

我收到错误消息说我正在比较指针和整数...为什么 “b”是整数吗?

这实际上意味着“b”是一个指针(它是 char 指针),而您的 line1[i] 是整数(实际上是一个 char)。

你也有同样的问题:

line2[i] = "B";  //<-- should be 'B' instead

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多