I am getting a segmentation fault when i run the follwing program.
This program takes in a const char* and returns the integer format.
I also need advice on converting a C++ Octal or Hexadecimal Notationed string to an integer.
Here is the code
#include <iostream>
#include <cstring>
int atoi(const char*);
int single_char_convert(char);
int pow(int,int);
int main()
{
std::cout<<atoi("123");
}
int atoi(const char *str)
{
int length=std::strlen(str)-1;
int result=0;
for(int x=0;x<=length;x++)
{
int y=length-x;
char character=str[x];
int converted_char=single_char_convert(character);
result+=(converted_char*pow(10,y));
}
return result;
}
int single_char_convert(char a)
{
switch(a)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
}
}
int pow(int number,int powerof)
{
if(powerof==1)
{
return number;
}
else
{
return number*pow(number,--powerof);
}
}
Code tags work sometimes and code tags donot work.