簡體   English   中英

為什么不能將char與“ *”進行比較?

[英]Why can't I compare char to “*”?

為什么我不能將UserInput[i]"*" 編譯器說“ ISO c ++禁止在指針和整數之間進行比較”。 整數在哪里? 我在那一行上看到的唯一一個是i ,它用於定位特定字符。

#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int main(){
    char UserInput[4] = "2*3";
    for (int i=0; i< strlen(UserInput); i++)
    {
        if(UserInput[i] == "*")
        {
            cout<<"There is multiplication Involved \n";
        }
    }
    return 0;
}

整數在哪里?

您的條件表達式是UserInput[i] == "*"

表達式UserInput[i]的類型為char 在許多二進制操作中,在執行操作之前,將char提升為int 就編譯器而言,它正在將int"*"進行比較, "*"const char[2]類型,但會衰減到表達式中的指針。

您需要做的是將char與字符常量'*' 采用

if(UserInput[i] == '*') {
if(UserInput[i] == "*")

將因“”發出警告

"*"不是字符。 "*"是一個const char*

指針與整數( intconst char * )之間的比較是不可能的

更改為

if(UserInput[i] == '*')

此外,使用std::string代替char數組

#include <iostream>
#include <string>
using namespace std;

int main() {
    string UserInput = "2*3";
    for (int i = 0; i < UserInput.length(); i++) {
        if (UserInput[i] == '*') {
            cout << "There is multiplication Involved \n";
        }
    }
    return 0;
}

這有點棘手。
中的所有內容都是字符串-字符數組。 c / c ++中的數組是指向數組第一個元素的指針。
字符串的每個元素都是char,它將轉換為int。
最后,編譯器說不可能比較這兩項。 您需要這樣做:

if(UserInput[i] == '*')

在這種情況下,您比較兩個字符毫無問題。

PS如果要確定另一個字符串中是否存在一個字符串,則應使用strstr()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM