2017-02-15 92 views
-3

我試圖找到如果一個字符串具有所有的唯一字符和以下是我的代碼,但我得到錯誤「數組下標」無效類型'char [int]'in函數Unique char的if語句,誰能告訴我如何解決這個問題要檢查一個字符串是否具有所有唯一字符在C + +

#include <iostream> 
#include<cstring> 

using namespace std; 
bool unique_char(char); 

int main() 
{ 
    char s; 
    bool check; 
    cout << "Enter any string" << endl; 
    cin>>s; 
    check = unique_char(s); 
    if(check) 
     cout<<"there are no duplicates"; 
    else 
     cout<<"the string has duplicates"; 

    return 0; 
} 

// The if statement in this section has the error 
bool unique_char(char s) 
{ 
    bool check[256] = {false}; 
    int i=0; 
    while (s != '\0') 
    { 
     if (check **[(int) s[i]]**) 
      return false; 
     else 
     { 
     check[(int) s[i]] = true; 
     i++; 
     } 

    } 
} 
+0

你覺得你可以裝入一個'char'字符多少個字符? –

+0

來自''標題的'std :: string'類型變量可以保存任意長度的文本字符串。 –

回答

0

您需要傳遞char數組而不是單個char。

int main() 
{ 
    char s[1000]; // max input size or switch to std::string 
    bool check; 
    cout << "Enter any string" << endl; 
    cin>>s; 
    check = unique_char(s); 
    if(check) 
     cout<<"there are no duplicates"; 
    else 
     cout<<"the string has duplicates"; 

    return 0; 
} 

bool unique_char(char* s) 
{ 
    bool check[256] = {false}; 
    int i=0; 
    while (s[i] != '\0') 
    { 
     if (check[(int) s[i]]) 
      return false; 
     else 
     { 
     check[(int) s[i]] = true; 
     i++; 
     } 
    } 
    return true; 
}