1

I am having trouble with converting string datatype to int in c++, I am currently using DevC++ GNU version 5.8.3 which gives an error when i use stoi() funtion. My concern is not about conversion but about the complexity and how it is done. Code Below :

#include<bits/stdc++.h>
int main(){
    string s="abc";
    int i=stoi(s,NULL,16);
}

Error : 'stoi' was not declared in this scope

So, i wrote my own function, Code Below :

String to Int :

int strtonum(string s,int length) {
    int num=0;
    for(int i=0;i<length;i++)
        num=num*10+(int)s[i]-48;
    return num;
}

Integer to String :

string numtostring(int number){
    int digit=floor(log10(number))+1;
    string s="";
    for(int i=0;i<digit;i++){
        s+=(char)(48+number%10);
        number/=10;
    }
    reverse(s.begin(),s.end());
    return s;
}

Both Functions are giving desired output, But I am worried about the complexity of Conversion.

For String to Int it is : O(n)

For Int to String it is : O(n)+O(n/2)

Q. Is there any better Solution to this problem ?

Q. How Complex are the Inbuilt Function

Q.How do they Convert one data type to another?

2 Answers2

0

You probably wanted to use atoi, and its complement strtod, or some related functions in this category.

0
Error : 'stoi' was not declared in this scope

try to add "std::"

//stoi // x

std::stoi(...) // ok
sailfish009
  • 2,561
  • 1
  • 24
  • 31