[英]How do I compare a double quotes string to a character?
我試圖在 c++ 中將字符串下標與帶有空格(“”)的字符串進行比較,但它返回了指針比較錯誤。 現在,當我嘗試將 "" 與 ' ' 進行比較時,顯然它並不相等。 當字符串的某個下標等於空格字符時,下面的代碼應該繼續 for 循環。
如果我將 substring 與“”進行比較,我會收到此錯誤: 16:22: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
請注意,當我在輸入變量中輸入一個空格時,它需要比較它。
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
vector<int> letters (26,0);
vector<char> alpha = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
bool flag;
cin >> input;
for(int i = 0; i < input.size();i++){
if(input[i]==' '){
continue;
}
cout << i;
for(int j = 0; j < alpha.size(); j++){
if(input[i]==alpha[j]){
letters[j] ++;
}
}
}
for (int i = 0; i < letters.size();i++){
if(letters[i] > 0){
cout << alpha[i] << ": " << letters[i] << endl;
}
}
}
有沒有辦法將空格字符與字符串進行比較?
據我所知,沒有辦法讓's' == "s"
工作。 但是您可以通過定義operator==
使's' == string("s")
工作:
// for 's'==string("s")
bool operator==(const char c, const string &s) { return c == s[0]; }
// for string("s") == 's'
bool operator==(const string &s, const char c) { return c == s[0]; }
它會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.