0
votes

I want to convert a character to Integer and calculate its frequency but I receive this error! I am using XCODE.

terminating with uncaught exception of type 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;

}

1
I'm pretty sure you don't need stoi - it makes no sense here. What's the expected input?Igor Tandetnik
Why are you passing an address of a string to stoi? It takes a const reference to a stringNathanOliver
@IgorTandetnik Input would be a string.yaoshinga
Of course it's a string. A string containing what characters though? Your program accepts input and produces output - show an example of expected input, and the example of the output the program is expected to produce given that input.Igor Tandetnik
@IgorTandetnik if I input "aaaaaabb" the array should have the value 6 at a[1] and 2 at a[2], considering 1-26 as alphabets in order a,b,c....zyaoshinga

1 Answers

0
votes

First check if its alpha character, then convert character to lowercase and then sub 'a' so you get value 0-25.

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

Also you have to initialize array a, because it is immediate

int a[26] = { 0 };

And if you want to print result

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

Here is the example.