2017-02-08 14 views
-1

我想從用戶那裏得到輸入字符串,以避免空間我用gets_s它輸出這樣的錯誤:無法獲取輸入字符串數據

enter image description here

char str[] = "", symb; 
    int count = 0; 
    cout << "Please enter String: "; 
    gets_s(str); 
    cout << "Which character you want to find: "; 
    symb = getchar(); 

    for (int i = 0; i < strlen(str); i++) 
    { 
     if (str[i]==symb) 
     { 
      count++; 
     } 
    } 

    cout << "Character: " << symb << " found " << count << " times."; 
+1

'gets_s(str);'是未定義的行爲。 –

+0

這是使用字符數組的工件。改用'std :: string'。 –

+5

不要使用char []','getchar'和'gets_s'。使用'std :: string','std :: getline'和'std :: cin'。 –

回答

0

在C++中常見的字符串輸入成語涉及std::stringstd::getline

string text; 
cout << "Please enter String: "; 
getline(cin, text); 

string包括搜索的方法,如find

相關問題