[英]How to iterate over std::vector<char> and find null-terminated c-strings
[英]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 ++標簽的正確性,您可能需要將word
和word1
聲明為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.