2012-08-05 53 views
0

作爲C++的初學者,我很長​​時間以來對這一點感到困惑,程序是告訴字符串中每個單詞出現的時間。strcmp(x,str)是錯誤的?

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

int main() 
{ 
    string x; 
    vector<string> str; 
vector<int> t; 
while (cin >> x) 
{ 
    int k = 0; 
    for (int j = 0; j != str.size(); j++) 
    { 
     if (strcmp(x,str[j]) == 0) 
      t[j]++; 
     k = 1; 
    } 
    if (k == 0) 
    { 
     str.push_back(x); 
     t.push_back(1);  
    } 

} 

for (int i = 0; i != str.size(); i++) 
{ 
    cout << str[i] << " " << t[i] << endl; 
} 

return 0; 
} 

以下是錯誤:

C++\code\3.3.cpp(17) : error C2664: 'strcmp' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const char *' 
     No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 

我在網上找了沒有結果經過較長時間的搜索之後。我怎樣才能解決這個問題?

+1

什麼是'y'?也是'std :: string'不能與'std :: strcmp'一起使用。 – Nawaz 2012-08-05 09:45:44

+1

一個字:*文檔* ... – 2012-08-05 09:46:59

+0

如果您需要strcmp的行爲,可以使用string :: compare作爲字符串。 – Cubic 2012-08-05 11:55:59

回答

1

如果x和y是C++字符串,那麼您只需說x == y。您正試圖在C++對象上使用C函數strcmp

如果y是一個C風格的字符串,則同樣的代碼x == y也將工作,因爲C風格的字符串將被自動轉換成C++風格的字符串,但是在這種情況下,它可能會更好做strcmp(x.c_str(), y) == 0,因爲這避免了自動轉換。

只有當x和y都是C風格的字符串時,您應該做strcmp(x, y) == 0

+0

沒有自動轉換是害怕的(除了可能在函數效果的描述中,它可以工作* as-if * doing'x == string(y)')。有一個'string :: compare(const char *)'重載,可以處理所有事情。 – 2012-08-05 10:11:05

+0

也許我還沒有走出c編程的風格..非常感謝! :) – Flaurel 2012-08-05 14:37:31

0

X是一個字符串,以及比較的strcmp爲const char * 將一個字符串轉換爲一個const char *使用

x.c_str() 
+0

thx!我現在明白了! – Flaurel 2012-08-05 14:22:46

1

這個錯誤是因爲STRCMP期望const char*是從std::string不同。您可以在該字符串檢索一個const char *調用方法c_str()

if (strcmp(x.c_str(),y) == 0) 

除此之外,似乎「Y」參數聲明無處您的代碼中。

+0

thx!對不起,它是「str [j]」不是「y」 – Flaurel 2012-08-05 14:23:52

-1

jahhaj是正確的,但如果你想打電話字符串C函數,你可以用string_instance.c_str()得到字符串作爲const char *

+0

thx !!我現在就試試吧,對不起,這是「str [j]」而不是「y」 – Flaurel 2012-08-05 14:25:33

0

編譯器期望const char*什麼可轉換到const char*。但std::string不會隱式轉換爲const char*

如果你想使用strcmp,你必須使用方法c_str得到一個const char*。但在你的情況下,最好使用==,它被重載以使用std :: string。

+0

thx !!對不起,這是「str [j]」而不是「y」 – Flaurel 2012-08-05 14:26:12