2

I'm trying to turn an int into string. I did it so far by getting the int with scanf, and then split it according to it's digits, and then put every one of the digits inside int array. Then I want to put all the int arr values inside a string, where the sign + or - will be the first character. Here is my code:

#include <stdio.h>
#include <string.h>
#define LENGTH 50
int getLength(int num, int arr[]);
int main()
{
    int num = 0, i = 0;
    int arr[LENGTH] = {0};
    char string[LENGTH] = {0};
    printf("enter number: ");
    scanf("%d", &num);
    int sizeMe = getLength(num, arr);
    string[2] = arr[2] + '0';
    printf("length %d one of values: %c", sizeMe,string[2]);
    for(i = 1; i < sizeMe + 1; i++);
    {
        string[i] = arr[sizeMe - i] + '0';
    }
    string[0] = '+';
    string[sizeMe] = 0;

    printf("string: %s", string);
}
int getLength(int num,int arr[])
{
    int count = 0;
    int i = 0, temp = 0;
    while(num != 0)
    {
        temp = num%10;
        num /= 10;
        count++;
        i++;
        arr[i] = temp;
        printf("index %d is %d\n",i,arr[i]);
    }

    return count;
}

The output of that program is just '+'. What did I do wrong here?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Gerimeni
  • 83
  • 1
  • 5
  • 5
    Why not simply use e.g. `sprintf`? – Some programmer dude Jan 19 '17 at 15:23
  • 3
    As for how to solve your problem with the code you have, then it's time to learn how to use a debugger. With a debugger you can step through code, line by line, while monitoring variables and their values. – Some programmer dude Jan 19 '17 at 15:25
  • 1
    As @Someprogrammerdude said, it is better to be lazy here and just use `sprintf`. – RoadRunner Jan 19 '17 at 15:49
  • @RoadRunner it's probably an exercise. – Jabberwocky Jan 19 '17 at 15:51
  • Hints: 1. Watch the trailing `;` right after `for (i = 0; i < sizeMe + 1; i++)`. 2. Watch your array indexes, if an array index is out of range, the program won't stop with an error, but you'll get undefined behaviour. 3. What do you think `string[0] = '+';` does? – Jabberwocky Jan 19 '17 at 15:56
  • @MichaelWalz that's fair enough. In that case, OP will learn more from debugging this code, than taking the shortcut of `sprintf`. – RoadRunner Jan 19 '17 at 15:58
  • Two more hints: 1. in `getLength` you can get rid of the `count` variable. It's a duplicate of `i` and it serves no purpose, however this is not the solurce of your problem. 2. Array indexes in C start at 0, not at 1 as in some other languages. – Jabberwocky Jan 19 '17 at 16:05
  • Code also has trouble with `num == 0`. Suggest `do { ... } while(num);` rather than `while(num != 0) { }`. – chux - Reinstate Monica Jan 19 '17 at 19:30

3 Answers3

2

The problem that is causing your code not to work is that you have a semicolon after the for statement like this:

for(i = 1; i < sizeMe + 1; i++);
{
    string[i] = arr[sizeMe - i] + '0';
}

That code would be equivalent to this:

for(i = 1; i < sizeMe + 1; i++){}
string[i] = arr[sizeMe - i] + '0';

So what's happening there is that only the last element of string is written in, the rest is left blank, which generates undefined behavior. To solve the problem, remove the semicolon. I also recommend putting the { at the end of the line of the for statement instead of on a new line since doing so would prevent you from making such mistakes. This is therefore the correct code, formatted in the way that I recommend formatting:

for(i = 1; i < sizeMe + 1; i++){
    string[i] = arr[sizeMe - i + 1] + '0';
}

Note that you also forgot the +1 in arr[sizeMe - i + 1].

Although that was the error that made your code not work the way you wanted it to work, you've also made several other mistakes, which could potentially cause your program to crash.

First of all, in the for loop, you're not testing if i is greater than LENGTH. The problem with that is that if i is greater than LENGTH, string[i] will be outside of the array, which will cause buffer overflow and make your program crash. To solve this problem, add the following code inside your for loop:

if(i + 1 > LENGTH){
    break;
}

The break statement will exit the for loop immediately. Note that we're testing if i + 1 is greater than LENGTH to leave space for the null character at the end of the string.

For the same reason, string[sizeMe] = 0; is also bad, since nothing says that sizeMe is less than the size of the array. Instead, use string[i] = 0;, since i has been incremented until it either reaches LENGTH or sizeMe. Therefore, i will be the minimum of these two values, which is what we want.

You also need to return something at the end of the main function. The main function is of type int, so it should return an int. In C++, this code wouldn't compile because of that. Your code compiled since you're using C and C compilers are generally more tolerant than C++ compilers, so you only got a warning. Make sure to fix all compiler warnings, since doing so can solve bugs. The warnings are there to help you, not to annoy you. Generally, the main function should return 0, since this value usually means that everything went well. So you need to add return 0; at the end of the main function.

Therefore, this is the code you should use:

#include <stdio.h>
#include <string.h>
#define LENGTH 50

int getLength(int num, int arr[]);
int main(){
    int num = 0, i = 0;
    int arr[LENGTH] = {0};
    char string[LENGTH] = {0};
    printf("enter number: ");
    scanf("%d", &num);
    int sizeMe = getLength(num, arr);
    string[2] = arr[2] + '0';
    printf("length %d one of values: %c", sizeMe,string[2]);
    for(i = 1; i < sizeMe + 1; i++){
        string[i] = arr[sizeMe - i + 1] + '0';
        if(i + 1 > LENGTH){
            break;
        }
    }
    string[0] = '+';
    string[i] = 0;

    printf("string: %s", string);

    return 0;
}

int getLength(int num,int arr[]){
    int count = 0;
    int i = 0, temp = 0;
    while(num != 0){
        temp = num%10;
        num /= 10;
        count++;
        i++;
        arr[i] = temp;
        printf("index %d is %d\n",i,arr[i]);
    }

    return count;
}

Also, as some programmer dude pointed out in a comment, it's much easier to use sprintf. Then your code would be much simpler:

#include <stdio.h>
#include <string.h>
#define LENGTH 50

int main(){
    int num = 0;
    char string[LENGTH] = {0};
    printf("enter number: ");
    scanf("%d", &num);
    sprintf(string, "%c%d", num >= 0 ? '+' : '-', num);
    printf("string: %s", string);
    return 0;
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
0

The short answer to turning a C int into a decimal string is to call sprintf(). That leads to the question how sprintf() does it.

From the book The C Programming Language, 2nd edition section 3.6. There is an example of a function that return a string representation of an integer. So here is the code:

void numberToString(int n, char *s){
    int i, sign;
    if ((sign = n) < 0) /*record sign*/
        n = -n; /* make n positive */

    i = 0;
    do { // generate digits in reverse order
        s[i++] = n % 10 + '0'; // get next digit*/
    } while ((n /= 10) > 0); // delete it

    s[i++] = sign < 0? '-': '+'; // or -- if(sign < 0) s[i++] = '-'; -- if you want just the sign '-'
    s[i] = '\0';

    strrev(s); //reverse the string
}

int main()
{
    int n;
    char str[LENGTH];

    printf("Number: ");
    scanf("%i", &n);

    numberToString(n, str);

    printf("Number as string: %s\n", str);
}

strrev is defined in the string.h header (so include it).

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

You can try and do this with sprintf. When you calculate the number length from get_length(), you can declare a string buffer, either statically or dynamically. Once declared, you can send the formatted output in the buffer with sprintf().

However, if you wish to still use your approach, @Donald Duck has covered the issues into debugging your code, and this is just another approach you can use if you want to.

Here is an example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

size_t get_length(int number);

int main(void) {
    int number;
    size_t numcnt;
    char *string;

    printf("Enter number: ");
    if (scanf("%d", &number) != 1) {
        printf("Invalid number entered\n");
        exit(EXIT_FAILURE);
    }

    printf("Number = %d\n", number);

    numcnt = get_length(number);

    string = malloc(numcnt+1);
    if (!string) {
        printf("Cannot allocate %zu bytes for string\n", numcnt+1);
        exit(EXIT_FAILURE);
    }

    sprintf(string, "%d", number);

    printf("String = %s\n", string);

    free(string);

    return 0;
}

size_t get_length(int number) {
    size_t count = 0;

    if (number < 0) {
        number *= -1;
        count++;
    }

    for (size_t i = number; i > 0; i /= 10) {
        count++;
    }

    return count;
}

Sample input 1:

Enter number: 1234

Sample output 1:

Number = 1234
String = 1234

Sample input 2:

Enter number: -1234

Sample output 2:

Number = -1234
String = -1234
RoadRunner
  • 25,803
  • 6
  • 42
  • 75