How To Convert Integer To String In C

Converting an integer to a string is frequently needed in C programming, for applications like printing or concatenation. This task can be accomplished through multiple methods such as sprintf(), itoa(), or snprintf().

The result is a string output that can be employed for various purposes. But it’s crucial to pick the right approach depending on aspects like speed, memory utilisation, and compatibility with different platforms and compilers.

Why there is need to convert integer to String in C

Here are the reasons:

  • In many programming situations, it may be necessary to display an integer value with a string message. In these circumstances, changing an integer value to a string will make it simple to concatenate it with a string message.
  • When working with files, data is usually stored in string format. Therefore, to write an integer value to a file, you need to convert it to a string first.
  • When integer numbers need to be concatenated with other values, they are frequently stored in database applications as strings.
  • To ensure system compatibility, integer values are communicated as strings in network programming.
  • Financial applications often require the manipulation of numeric data in string format.
  • Games often involve keeping track of player scores or levels, which are usually represented as integers that need to be displayed in a string format.
  • Finally, converting integers to strings is essential for formatting output, such as when displaying the date and time in a specific format.

Approaches

  1. Using sprintf().
  2. Using snprintf().
  3. Using a loop and modulus operator.

Approach 1: Using sprintf()

The sprintf() method is widely used to convert integers to strings in C programming.

It is a part of the standard C library and works by writing formatted output to a string buffer.

Advantages of using sprintf() method:

  • sprintf() offers flexibility in formatting the output string, allowing customization of the format string to include various formatting options such as decimal places, leading zeros, and padding spaces.
  • The method is widely supported by different platforms and compilers, making it a reliable and portable method for converting integers to strings.

Disadvantages of utilising the sprintf() method:

  • The potential influence on memory utilisation is one of the main disadvantages of using sprintf().
  • Moreover, the time complexity of the sprintf() method is relatively high, making it less efficient compared to other methods like itoa() and snprintf().
  • To summarise, the sprintf() method is a popular and reliable way to convert integers to strings in C programming, offering flexibility in formatting the output string.

Code :

#include <stdio.h>

int main() {
   int num = 1208;
   char str[10];
   
   sprintf(str, "%d", num);
   printf("The string representation of %d is %s\n", num, str);
   
   return 0;
}

Output :

The string representation of 1208 is 1208

Explanation :

  1. The code starts by including the necessary header file stdio.h, which contains the declaration of standard input/output functions.
  2. Inside the main() function, an integer variable num is declared and initialised with the value 1208.
  3. A character array str of size 10 is also declared to store the string representation of the integer.
  4. The sprintf() method is called with the buffer str, the format string “%d”, and the integer variable num as arguments. The format string specifies that the integer value should be converted to a decimal string. The resulting string is stored in the str buffer.
  5. Output is printed with printf().
  6. The main() function returns 0, indicating successful program execution.

Approach 2 : Using snprintf().

The snprintf() method is another commonly used approach to convert an integer to a string in C programming. The function writes the output string to the buffer while ensuring that it does not exceed the size supplied, preventing buffer overflows and memory corruption.

Advantages:

  • Because it avoids buffer overflows, the approach is safer to use than sprintf().
  • It provides control over the maximum length of the output string.
  • Like sprintf(), it supports formatting options for the output string.

Disadvantages:

  • The time complexity of the snprintf() method is relatively high, making it less efficient than other methods like itoa().
  • The size of the buffer must be specified correctly to avoid truncation of the output string.
  • The snprintf() method may not be available on some older compilers or platforms.

Code :

#include <stdio.h>

int main() {
    int num = 1234;
    char buffer[10];
    int length = snprintf(buffer, 10, "%d", num);
    printf("String: %s\n", buffer);
    printf("Length: %d\n", length);
    return 0;
}

Output :

String : 1234
Length : 4

Explanation :

  1. The code starts with the inclusion of the standard input/output library header file “stdio.h”.
  2. The main() function is defined that returns an integer value.
  3. An integer variable “num” is declared and assigned a value of 1234.
  4. A character array “buffer” of size 10 is declared.
  5. The “snprintf()” function is called with four arguments – “buffer”, 10 (size of the buffer), “%d” (format string to represent an integer), and “num” (the integer to be converted to a string).
  6. The “snprintf()” function converts the integer “num” to a string format and stores it in the buffer “buffer” with the specified format (“%d”).
  7. It also returns the length of string.
  8. Two “printf()” statements are used to output the generated string and its length on the console.
  9. Finally, the main() function returns 0, indicating successful execution of the program.

Approach 3: Using a loop and modulus operator

A loop and the modulus operator are two more prominent methods for converting an integer to a string in C. The modulus operator is used to extract each digit as the method iterates across the integer digits from right to left. The final string is produced by converting each digit to its matching ASCII code and storing it in reverse order in a character array.

Code :

#include <stdio.h>

void int_to_str(int num, char* str) {
    int i = 0;
    int is_negative = 0;
    
    if (num < 0) {
        is_negative = 1;
        num = -num;
    }
    
    do {
        str[i++] = num % 10 + '0';
        num /= 10;
    } while (num > 0);
    
    if (is_negative) {
        str[i++] = '-';
    }
    str[i] = '\0';
    
    int j = 0;
    while (j < i/2) {
        char temp = str[j];
        str[j] = str[i-j-1];
        str[i-j-1] = temp;
        j++;
    }
}

int main() {
    int num = -1208;
    char buffer[10];
    int_to_str(num, buffer);
    printf("String: %s\n", buffer);
    return 0;
}

Output :

String : -1208

Explanation :

  1. This code defines the function int_to_str(), which accepts an integer and a character array as input and returns the integer’s string representation.
  2. The function first handles negative numbers by setting a flag and converting the number to its absolute value.
  3. It then extracts each digit from right to left using the modulus operator and stores it in the character array in reverse order.
  4. Finally, it adds a negative sign if applicable, terminates the string with a null character, and reverses the string.
  5. In the main function, an integer is declared and passed to the int_to_str() function along with a character array. Output is printed with printf().

Best Approach : Using the loop and modulus operator

In C programming, the method that involves utilising a loop and the modulus operator is an acceptable strategy for converting an integer to a string. Here are the reasons:

  • One of the major advantages of this is its memory efficiency.
  • This solution has a low time complexity, making it more efficient than methods like sprintf() and snprintf().
  • This is also a beginner-friendly method for C programmers.
  • The loop and modulus approach achieves a good balance of efficiency, memory utilisation, and code simplicity, making it a good choice for converting numbers to strings in most cases.

Sample Problem

Sample Problem 1 :

At IBM  company, John works as a software developer and is entrusted with developing a programme that generates an employee information report. Each employee’s information is maintained in the form of a struct, which includes the following fields: name (a string), age (an integer), wage (a float), and employee ID (an integer).

Solution:

  1. The code defines a struct called “Employee” which contains the fields: name, age, salary, and id.
  2. The function “generateReport” takes in an array of employee structs and the number of employees as arguments.
  3. Inside the “generateReport” function, a character buffer of size 100 is created to store the formatted output string for each employee.
  4. The function starts by printing the header of the report.
  5. A loop is used to iterate through the array of employees and format each employee’s information as a string using sprintf() method. The formatted string is then printed out using printf() method.
  6. The main function initialises an array of Employee structs and calls the “generateReport” function with the array and number of employees as arguments.
  7. The output of the program is a report containing the information of each employee in the specified format.

Code :

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

struct Employee {
    char name[50];
    int age;
    float salary;
    int id;
};

void generateReport(struct Employee employees[], int n) {
    char buffer[100];
    printf("Employee Information Report:\n");
    for (int i = 0; i < n; i++) {
        sprintf(buffer, "Employee ID: %d, Name: %s, Age: %d, Salary: %.2f", employees[i].id, employees[i].name, employees[i].age, employees[i].salary);
        printf("%s\n", buffer);
    }
}

int main() {
    struct Employee employees[5] = {
        {"John Doe", 28, 55000.00, 101},
        {"Jane Smith", 32, 72000.00, 102},
        {"Bob Johnson", 41, 93000.00, 103},
        {"Sarah Lee", 24, 45000.00, 104},
        {"Tom Smith", 36, 66000.00, 105}
    };
    generateReport(employees, 5);
    return 0;
}

Output :

Employee ID: 102, Name: Jane Smith, Age: 32, Salary: 72000.00
Employee ID: 103, Name: Bob Johnson, Age: 41, Salary: 93000.00
Employee ID: 104, Name: Sarah Lee, Age: 24, Salary: 45000.00
Employee ID: 105, Name: Tom Smith, Age: 36, Salary: 66000.00

Sample Problem 2:

John and David are working on a system that handles financial transactions for a bank. As part of the system, they need to generate reports of customer transactions in a specific format. Each transaction has a transaction ID, an amount, and a date.

Solution:

  1. The code begins by defining a struct for transactions, which contains an integer ID, a floating-point amount, and a struct tm for the date.
  2. The main() function initialises an array of three sample transactions for testing purposes.
  3. The generate_report() function takes in an array of transactions and the number of transactions. It defines a character array of size 100 for storing the output string and an integer for storing the length of the output string.
  4. The function then loops through each transaction in the array, using snprintf() to convert the ID, amount, and date values to strings and store them in the output array.
  5. If the output length exceeds its limit then it will generate an error.
  6. If the output string is successfully generated, the function prints it out to the console.

Code :

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

struct transaction {
    int id;
    double amount;
    struct tm date;
};

void generate_report(struct transaction transactions[], int num_transactions) {
    char output[100];
    int length;

    for (int i = 0; i < num_transactions; i++) {
        length = snprintf(output, sizeof(output), "Transaction ID: %d, Amount: %.2f, Date: %d/%d/%d",
            transactions[i].id, transactions[i].amount, transactions[i].date.tm_mday, 
            transactions[i].date.tm_mon + 1, transactions[i].date.tm_year + 1900);

        if (length > sizeof(output)) {
            printf("Error: Output string was truncated.\n");
            return;
        }

        printf("%s\n", output);
    }
}

int main() {
    struct transaction transactions[3];

    transactions[0].id = 1234;
    transactions[0].amount = 100.25;
    transactions[0].date.tm_mday = 1;
    transactions[0].date.tm_mon = 0;
    transactions[0].date.tm_year = 122;

    transactions[1].id = 5678;
    transactions[1].amount = 50.10;
    transactions[1].date.tm_mday = 15;
    transactions[1].date.tm_mon = 6;
    transactions[1].date.tm_year = 121;

    transactions[2].id = 9101;
    transactions[2].amount = 500.00;
    transactions[2].date.tm_mday = 25;
    transactions[2].date.tm_mon = 3;
    transactions[2].date.tm_year = 119;

    generate_report(transactions, 3);

    return 0;
}

Output :

Transaction ID: 1234, Amount: 100.25, Date: 1/1/2022
Transaction ID: 5678, Amount: 50.10, Date: 15/7/2021
Transaction ID: 9101, Amount: 500.00, Date: 25/4/2019

Sample Problem 3:

John and Leo are working on a project where you need to store and display the number of products available in stock. The products are identified by an integer ID number, and they need to display the stock count as a string. Write a code to convert this stock integer to string.

Solution:

  1. The intToString function takes two parameters, an integer num and a character array str to store the resulting string.
  2. The function initialises two integer variables, i and j, to 0 and a character variable temp to hold temporary values during the string reversal process.
  3. The function handles negative numbers by adding a minus sign to the beginning of the string and making the number positive.
  4. A while loop is used to convert each digit of the number to a character and store it in the string. This is done using the modulus operator to get the remainder when the number is divided by 10, and adding the ASCII code for the digit ‘0’.
  5. After all digits have been added to the string, it is reversed using a while loop that swaps the string’s initial and last characters until the string’s midpoint is reached.
  6. Finally, the string is terminated using a null terminator.
  7. In the main function, an integer variable stockCount is initialized to the value 125, and a character array stockCountStr is initialized to hold the resulting string.
  8. The intToString function is called to convert the stockCount integer to a string, and the resulting string is stored in stockCountStr.

Code :

#include <stdio.h>

void intToString(int num, char *str) {
    int i = 0, j = 0, k;
    char temp;

    if (num < 0) {
        str[j++] = '-';
        num = -num;
    }

    while (num != 0) {
        str[i++] = num % 10 + '0';
        num /= 10;
    }

    k = i - 1;
    while (j < k) {
        temp = str[j];
        str[j++] = str[k];
        str[k--] = temp;
    }

    str[i] = '\0';
}

int main() {
    int stockCount = 1207;
    char stockCountStr[10];

    intToString(stockCount, stockCountStr);

    printf("Stock Count: %s\n", stockCountStr);

    return 0;
}

Output :

Stock Count : 1207

Conclusion

In conclusion,there are numerous techniques available to convert numbers to strings, which is a task that frequently arises in programming. The most popular method is loops using the modulus operator can be useful if more control over the conversion process is required.

Through adequate memory allocation and error handling, potential mistakes like buffer overflows and issues with string termination should be avoided. You can select the optimal strategy by being aware of the project’s possibilities and requirements.