2017-08-24 47 views
0

我想將字符轉換爲Integer並計算其頻率,但是我收到此錯誤!我正在使用XCODE。以std :: invalid_argument類型的未捕獲異常結束:stoi:無轉換(lldb)

以類型std :: invalid_argument:stoi:no conversion未捕獲的異常終止。

#include <iostream> 

int main(int argc, const char * argv[]) { 
std::string s; 
std::cin>>s; 

int a[27]; 
for(int i=0;i<s.length();i++) 
{ 
    int c; 
    c=std::stoi(&s[i]); 
    a[c]++; 
} 
for(int i=0;i<27;i++) 
    std::cout<<a[i]; 

return 0; 

}

+0

我很確定你不需要'stoi' - 這裏沒有意義。預期的輸入是什麼? –

+0

爲什麼你將一個字符串的地址傳遞給'stoi'? [它需要一個'const'引用字符串](http://en.cppreference.com/w/cpp/string/basic_string/stol) – NathanOliver

+0

@IgorTandetnik輸入將是一個字符串。 – yaoshinga

回答

0

首先檢查它的字母字符,然後轉換角色爲小寫再分「A」,所以你得到的值0-25。

if (isalpha(s[i])) 
{ 
    c= tolower(s[i]) - 'a'; 
    a[c]++; 
} 

你也需要初始化數組a,因爲它是立即

int a[26] = { 0 }; 

如果你想打印結果

for(unsigned int i=0;i<(sizeof(a)/sizeof(a[0]));i++) 
{ 
    std::cout << a[i]; 
} 

Here is the example.

+0

謝謝!這有助於 – yaoshinga

+0

@yaoshinga所以你可以把它標記爲回答:-) –

相關問題