Convert string to int and Reverse in C and C++

This post introduces how to convert string to int and int to string in C and C++.

Convert string to int

1. The C way

Use C standard library

    #include <cstdlib>
    #include <string>
    std::string text = "123";
    int number = std::atoi (text.c_str ());
    if (errno == ERANGE)
     //or may be std::errno
    {
       // the number is too big/small
       // number = LONG_MAX or LONG_MIN
    }
    else if (errno == ????)
    //maybe EINVAL, E2BIG or EDOM (or ERANGE again)
    {
       //unable to convert to a number
    }

2. The C++ way

Use C++ standard library

    #include <sstream>
    #include <string>
    std::string text = "123";
    int number;
    std::istringstream iss (text);
    iss >> number;
    if (!iss.good ()) {
       //something happened
    }

Convert int to string

1. The C way

Use C standard library

    #include <stdio.h>
    
    const char base_string[] = "base_string";
    char out_string [MAX_BUFFER_SIZE];
    int number = 123;
    sprintf(out_string, "%s%d", base_string, number);
    printf("out_string = "%s"n", out_string);

2. The C++ way

Use C++ standard library

    #include <sstream>
    
    int i = 123;
    std::string out_string;
    std::stringstream ss;
    ss << i;
    out_string = ss.str();

References:

Eric Zhiqiang Ma

Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *