3

How can I convert a string to an array without using atoi, atol, isdigit, anything like that?

Assume I have a const char *str and a int *converted_val as parameters.

Here's what I have:

const char *c;
    for(c = str; (*c != '\0') && isdigit(*c); ++c){
                    *converted_value = *converted_value*10 + *c - '0';
    }
    return true;

but once again, I can't do it without isdigit. And I'm not sure how to handle strings that are large (for instance: "10000000000000000")

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Mike Henke
  • 641
  • 2
  • 10
  • 24

4 Answers4

4
int yetAnotherAtoi(char *str)
{
 int res = 0; // Initialize result

 // Iterate through all characters of input string and
 // update result
 for (int i = 0; str[i] != '\0'; ++i) {
     if (str[i]> '9' || str[i]<'0')
         return -1; # or other error...
     res = res*10 + str[i] - '0';
 }

 // return result.
 return res;
}
Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36
3

Substitute isdigit(*c) by *c >= '0' && *c <= '9':

const char *c;
....
for( c = str; *c != '\0' && *c >= '0' && *c <= '9'; ++c) {
    *converted_value = (*c - '0') + *converted_value*10;
}
return true;

Note that ASCII signs '0' to '9' are in ascending order.

You are limited to the range of the integral datatype of converted_value.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Yes! Perfect! Any idea how I would handle large cases? *str = "10000000000"? – Mike Henke Feb 11 '16 at 05:55
  • Actually, consecutivity of `0` through `9` is guaranteed by the standard, ASCII or not. The same is **not** true for `a` through `z`. – DevSolar Feb 11 '16 at 05:56
  • 3
    @MikeHenke You are limited to the range of your integratl datatype of `converted_value`. – Rabbid76 Feb 11 '16 at 05:56
  • You should be checking for overflow within your conversion against INT_MAX (and INT_MIN) and handle the error condition. Or change your type to *long* (or the 64-bit type on your system, perhaps int64_t). You then need to check against the limit for the 64-bit type and handle the error. – David C. Rankin Feb 11 '16 at 06:10
2

Change:

int *converted_val

to

long int *converted_val

to have more space for larger values. You might also consider adding code to check if the input string is going to overflow your output variable.

ammon0
  • 31
  • 3
0

if you want string to integer without use function in Visual Studio you can do like below code:

#include "stdafx.h"
#include<iostream>
#include<string>
#include<conio.h>
using namespace std;

int main()
{

    std::string str ;
    getline(cin, str);
    int a = 0;
    for (int i = 0  ; i<str.length(); i++) {
        a = (int)(str[i] - 48) + a * 10;
    }
    cout << a;

    _getch();
    return 0;
}
msn
  • 11
  • 2