Function of stoi() in c++

143 viewsC++programming programming language
1

void recursion(string state,int pos){
    int i,ind,temp,x;
    bool flag = false;
    temp = stoi(state,nullptr,2);
    x=temp;
    if(visited[temp]) {
        return;
    }
    visited[temp]++;
    for(i = state.size()-1;i >= 0; i-- ){
        if(state[i] == '0'){
            flag = true;
            ind = state.size() - i;
            temp = temp>>ind;
            temp = temp | ICV;
            string inter = "";
            while(temp!=0){
                int x;
                x = temp%2;
                inter = to_string(x) + inter;
                temp/=2;
            }
            adj[{state,pos}].push_back(make_pair(inter,ind));
            temp = x;
            recursion(inter,ind);
        }
    }
    if(!flag){
        adj[{state,pos}].push_back(make_pair(icv,times));
    }
    visited[temp]--;
}

use of stoi() in c++?

Answered question
2

In c++, stoi() function convert string to integer syntax:

int stoi (const string&  str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);

this function parse string interpreting some integral value or number of a specified base which is returned as an integer value. please have a look at this program

// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi
 int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";
   std::string::size_type sz;   // alias of size_t
   int i_dec = std::stoi (str_dec,&sz);
  int i_hex = std::stoi (str_hex,nullptr,16);
  int i_bin = std::stoi (str_bin,nullptr,2);
  int i_auto = std::stoi (str_auto,nullptr,0);
   std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
  std::cout << str_hex << ": " << i_hex << '\n';
  std::cout << str_bin << ": " << i_bin << '\n';
  std::cout << str_auto << ": " << i_auto << '\n';
   return 0;
}

output would be

2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3:  16579
-10010110001: -1201
0x7f: 127
Changed status to publish