-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathConvertStringToInteger.cpp
More file actions
105 lines (84 loc) · 2.21 KB
/
ConvertStringToInteger.cpp
File metadata and controls
105 lines (84 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
Recursion - Convert String To Integer
Take as input a number in form of a string.
Write a recursive function to convert the number in string form to number in integer form.
*/
#include<iostream>
using namespace std;
int i=0;
int main()
{
char str[10];
int x, checkFormat(char []);
long num, StrToInt(char []);
cout<<"Enter a number : ";
cin>>str; //since cin ignores or will not read white spaces or tabs or newline characters.
x=checkFormat(str);
if(x==1) //if entered number contains only digits.
{
num=StrToInt(str);
cout<<"\nNumber in integer format : "<<num<<endl;
}
else if(x==0) //if entered number starts with zero and does not contain any other special symbol
{
num=StrToInt(str+1);
cout<<"\nNumber in integer format : 0"<<num<<endl;
}
else if(x==-1) //if entered number starts with a -ve sign.
{
num=StrToInt(str+1);
cout<<"\nNumber in integer format : -"<<num<<endl;
}
else if(x==-2) //if entered number starts with +ve sign.
{
num=StrToInt(str+1);
cout<<"\nNumber in integer format : +"<<num<<endl;
}
else //if entered number contains special symbol.
cout<<"\nEntered number contains some special character!!!\n";
return 0;
}
int checkFormat(char str[])
{
if(str[0]-'0'==0)
{
for(int j=0; str[j]!='\0'; j++)
if(!(isdigit(str[j])))
return -5;
return 0;
}
else if(str[0]=='-')
{
for(int j=0; str[j]!='\0'; j++)
if(!(isdigit(str[j])))
return -5;
return -1;
}
else if(str[0]=='+')
{
for(int j=0; str[j]!='\0'; j++)
if(!(isdigit(str[j])))
return -5;
return -2;
}
else
{
for(int j=0; str[j]!='\0'; j++)
if(!(isdigit(str[j])))
return -5;
}
return 1;
}
long x, number=0;
long StrToInt(char str[])
{
if(str[i]!='\0')
{
x=str[i]-'0';
number*=10;
number+=x;
i++;
StrToInt(str);
}
return number;
}