簡體   English   中英

如何比較char變量(c字符串)?

[英]How to compare char variables (c-strings)?

#include <iostream>
using namespace std;

int main() {
    char word[10]="php";
    char word1[10]="php";

    if(word==word1){
        cout<<"word = word1"<<endl;
    }

return 0;
}

我不知道如何比較兩個字符字符串以檢查它們是否相等。 我當前的代碼無法正常工作。

使用strcmp。

#include <cstring>
// ...
if(std::strcmp(word, wordl) == 0) {
// ...
}

使用std::string對象代替:

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

int main() {
    string word="php";
    string word1="php";

    if(word==word1){
        cout<<"word = word1"<<endl;
    }

return 0;
}

為了證明c ++標簽的正確性,您可能需要將wordword1聲明為std::string 根據需要進行比較

if(!strcmp(word,word1)) {

您提交的代碼中的word和word1是指針。 因此,當您編寫代碼時:

word==word1

您正在比較兩個內存地址(這不是您想要的地址),而不是它們指向的c字符串。

#include <iostream>
**#include <string>** //You need this lib too

using namespace std;

int main() 
{

char word[10]="php";
char word1[10]="php";

**if(strcmp(word,word1)==0)** *//if you want to validate if they are the same string*
    cout<<"word = word1"<<endl;
*//or*
**if(strcmp(word,word1)!=0)** *//if you want to validate if they're different*
    cout<<"word != word1"<<endl;

return 0;``
}

暫無
暫無

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

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