Problem turning string into int: "error: no matching Function for call to stoi"

Asked

Viewed 455 times

0

I’m writing a little show input a string of integer numbers as a string and as output an array with twice each of the numbers, also as a string. Despite the function atoi be indicated in that reply, li here that it is better to use the function std::stoi.

It happens that when I try to transform the string for int using std::stoi, the program returns the following error:

 error: no matching function for call to ‘stoi(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)’

Below is my code for error replication:

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

using namespace std; 

int main(){
    string var1="1234";
    vector <string> empty(4,"a");
    for (int i=0;i<4;i++){
        int var2=stoi(var1[i]);
        empty[i]=2*var2;
    }
    for (string x : empty){
        cout<<x<<endl;
    }
    return 0;
}

Why this error is occurring and how do I correct?

  • You are using the function stoi wrong way. Try: std::string::size_type sz; int var2=stoi(var1, &sz);

1 answer

1


You do not need to use this function. What returns in var1[i] is a character, so neither could use this function that expects a string.

I put in the code the simplest way to convert a character into a digit (I did not validate if it is a digit, because then several other things would need to be validated or made generic).

And converted the result to string since it would make another mistake then by trying to save a number in a place that expects a string. I don’t even know if I should be string there.

#include <iostream>
#include <vector>
#include <string>
using namespace std; 

int main(){
    auto var1 = "1234";
    vector<string> empty(4, "a");
    for (auto i = 0; i < 4; i++) empty[i] = to_string(2 * (var1[i] - '0'));
    for (auto x : empty) cout << x << endl;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • 1

    because var1[i] is not var1, until you read you can notice that they are different things. var1 is string, var1[i] is a helmet of var1 what is an element of a text? A character is not another text. Put otherwise the operator [] is set in the object to returns a char.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.