+ 6
Parsing string integer value to normal integer?
How to parse a string integer to a normal integer? eg: string str="ahd14sjd"; int a; for(int I=0;I<str.length();I++) { if(str[I]=='1') a=str[I]; } cout<<a; In above example, The value of 'a' will be ASCII value of 1. but I want to assign 'a' as 1 and print 'a' as 1. how can I do that? (I.e) parsing string integer to a integer? I hope you understood my question.
2 Réponses
+ 3
string str="ahd14sjd";
int a=0;
int c=1;
for(int i=str.length();i>=0;i--){
if(str[i]>='0'&&str[i]<='9'){
a += (str[i]-'0')*c;
c *= 10;
}
}
cout << a;
+ 1
The ascii value of 'a' is 97 as an int. If you're trying to get the Integer value of a character, all you need to do is cast the char to an int.
int('a')