Checkout the below program written to convert numbers in string to integer. In C++ there is a function atoi() to convert number in character to integer. Here I am writing my own function to to do this.
//atoi() function creation.
#include<iostream>
using namespace std;
bool isNumeric(char x)
{
return(('0'<= x && x <='9')?true:false);
}
int myAtoi(char* str)
{
int neg = 1, res = 0, i = 0;
if(str[0] == '-'){
neg=-1;
i++;
}
while(str[i]!='\0'){
if(!isNumeric(str[i])){
return(res*neg);
}
else
{ res = res*10 + str[i]-'0'; i++; }
}
return(res*neg);
}
int main()
{
char str[]="-90jyh8";
int val = myAtoi(str);
cout<<val;
return 1;
}
Output::-90
//atoi() function creation.
#include<iostream>
using namespace std;
bool isNumeric(char x)
{
return(('0'<= x && x <='9')?true:false);
}
int myAtoi(char* str)
{
int neg = 1, res = 0, i = 0;
if(str[0] == '-'){
neg=-1;
i++;
}
while(str[i]!='\0'){
if(!isNumeric(str[i])){
return(res*neg);
}
else
{ res = res*10 + str[i]-'0'; i++; }
}
return(res*neg);
}
int main()
{
char str[]="-90jyh8";
int val = myAtoi(str);
cout<<val;
return 1;
}
Output::-90
No comments:
Post a Comment