0

i'm working on a code right now in C++, in which i'm supposed to make a function which receives a string of numbers and converts it into an integer then returns that value. for example if i pass "4569" as string, it will return 4569 integer value. can anyone help me point out where i'm wrong ??? thanks in advance :)

#include<iostream>
#include<cstdlib>
using namespace std;

void getInput(char arr[] , int size )
{
    cout<<"ENTER THE ARRAY"<<endl;
    cin.getline(arr,size);

}

int stringToInteger(char source[])
{
    int sum = 0;
    int y=strlen(source);
    int multiply = 1;
    for( int i=y ; i>=0 ; i--)
    {
        int n= source[i];
        sum = (sum + (n * multiply));
        multiply = (multiply *10);
    }
    return sum;
}

int main()
{
    const int size =100;
    char inputArr [size];
    getInput (inputArr, size );

    int x = stringToInteger (inputArr );
    cout<<"THE RETURNED INTEGER VALUE IS"<<endl;
    cout<<x<<endl;
    return 0;
}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
Kady
  • 1
  • 2

4 Answers4

2

First, you're starting at the character after the end of the string. If the length (returned by strlen) is y, then valid indexes are 0 <= i < y. So your loop wants to start from y-1.

for( int i=y-1 ; i>=0 ; i--)
            ^^

Then, you need to convert each ASCII digit into a value from 0 to 9, by subtracting the ASCII value for '0':

int n= source[i] - '0';
                 ^^^^^

Then you should probably detect and handle erroneous input, including values that are too large to be represented by int.

Then, once you've learnt how to implement this in C, throw it away and use the C++ library:

std::string input;
std::getline(std::cin, input);
int x = std::stoi(input);
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • The `atoi` function has been a part of the standard __C__ library for at least 20 years. – Steve Barnes Aug 14 '13 at 17:54
  • I thought `atoi` is deprecated nowadays in favor of `strol`? – Dennis Meng Aug 14 '13 at 17:58
  • @SteveBarnes: Indeed, if you don't care about error handling. But what's that got to do with a question about C++ (even if it is mistagged with C, and written with C idioms)? – Mike Seymour Aug 14 '13 at 17:59
  • Don't know about the C library but I remember using atoi in 1979. http://stackoverflow.com/questions/2909768/where-did-the-name-atoi-come-from says it was in the 1971 Unix (but not C) manual. – cup Aug 14 '13 at 18:00
  • A left-to-right implementation is better than doing `strlen` at all. – Carl Norum Aug 14 '13 at 18:11
1

Try,

#include <stdlib.h>

and in your main():

int x = atoi(inputArr);
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
0

I'm not sure why you aren't using atoi or std::stoi, but your algorithm has a logical flaw:

int stringToInteger(char source[])
{
    int sum = 0;
    int y=strlen(source);
    int multiply = 1;
    for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
    {
        int n = (int)(source[i] - '0');
        sum += (n * multiply); // += makes this more readable
        multiply *= 10; // same with  *=
    }
    return sum;
}

That said, if this was something other than a homework assignment, you should be using the solutions posted https://stackoverflow.com/a/18238566/529761 or https://stackoverflow.com/a/18238682/529761 (depending on your language requirements).

Also, even this change has 1 potential problem: If the source contains non-numeric characters, it will not work properly. A simple way to approach it is to break out if you encounter a character that shouldn't be there:

int stringToInteger(char source[])
{
    int sum = 0;
    int y=strlen(source);
    int multiply = 1;
    for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
    {
        int n = (int)(source[i] - '0');
        if (n < 0 || n > 9)
            break;
        sum += (n * multiply); // += makes this more readable
        multiply *= 10; // same with  *=
    }
    return sum;
} 
Community
  • 1
  • 1
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
0

No need to call a strlen -- until you are allowed to use library functions (the above-mentioned atoi and strtol), you can use this:

int stringToInteger(char *source)
{
  int sum = 0;
  if (source)
    while (*source >= '0' && *source <= '9')
    {
      sum = 10*sum + *source - '0';
      source++;
    }
  return sum;
}

As implied in about every other answer, you forgot there is a difference between the ASCII character '0' and the binary value 0.

Jongware
  • 22,200
  • 8
  • 54
  • 100