Last active
October 19, 2015 14:22
-
-
Save codebucketdev/5cf82d858a2d4d06ad0c to your computer and use it in GitHub Desktop.
This snippet parses an int32 from a string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstring> | |
using namespace std; | |
int multiplier(int n) | |
{ | |
if (n == 0) | |
return 1; | |
int q = 10; | |
for (int i = 0; i < n - 1; i++) | |
{ | |
q *= 10; | |
} | |
return q; | |
} | |
int string2int(char s[]) | |
{ | |
if (strlen(s) == 0) | |
return 0; | |
bool r = s[0] == '-'; int n = 0; | |
for (int i = r; i < strlen(s); i++) | |
{ | |
int c = (s[i] - 48) * multiplier(strlen(s) - i - 1); | |
if (!r) | |
n += c; | |
else | |
n -= c; | |
} | |
return n; | |
} | |
int main() | |
{ | |
char s[64]; | |
scanf("%s", s); | |
printf("%d", string2int(s)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment