Home > OS >  convert str[i] into integer type using stoi()
convert str[i] into integer type using stoi()

Time:01-07

I have a string of number and I want to convert each number into integer type then add it into a vector.

    #include<bits/stdc  .h>
    #include<string>
    #include<vector>
    using namespace std;

    int main() {
        vector<int> vec;
        string num;
        cin >> num;
        for(int i = 0; i <= num.length(); i  ){
            vec.push_back(stoi(num[i]));
        }
        return 0;
    }

it said error: no matching function for call to stoi

CodePudding user response:

First of all, you should definitely not use #include<bits/stdc .h> and using namespace std; in your code. They use it in platforms like LeetCode and HackerRank but it really isn't a good practice. So, as you are starting out, try avoiding it. Check out namespaces in C , this will give you a good idea.

Now, to your problem: i <= num.length(); here, the = will make you go out of range. Also stoi works on strings, not chars.

Here is some code to help you out.

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

int main(void){
    std::vector <int> vec;

    std::string str;
    std::cin >> str;

    for(int i = 0; i < str.length(); i  ){
        vec.push_back(std::stoi(str.substr(i, 1))); // stio requires you the pass a string.
                                                    // So passing a character like str[i] won't work.
                                                    // We will need to convert each character into a substring.
    }

    return 0;
}

  • Related