Want to Join Us ?

you'll be able to discuss, share and send private messages.

Tutorial Conversion of int to string

Discussion in 'Tutorials' started by dila, Sep 22, 2015.

Share This Page

  1. dila

    Member

    • dila
    • Sep 17, 2015
    • 10
    • 12
    This is really simple, and most people would recommend boost::lexical_cast for this purpose, which is nice if you have boost (apart from the mess of handling the exceptions), but if you just have straight c++ you can still do it without any special utility routines like this:

    Code (Text):
    #include <iostream>
    #include <sstream>
     
    int main()
    {
      int x = 12345;
     
      std::stringstream y;
     
      y << "The number is: " << x;
     
      std::cout << y.str() << std::endl;
     
      return 0;
    }
     
    You can see that the str() method of the std::stringstream object just returns you an std::string.

    Happy coding :)
     
    Rip Cord, Surge1223 and storm shadow like this.
  2. dila

    Member

    • dila
    • Sep 17, 2015
    • 10
    • 12
    I discovered that std::stringstream can also be used to parse to integer again. Attached is a small program that reads a bunch of integers from the command line, adds them together, and prints the result.

    Code (C):
    #include <iostream>
    #include <sstream>
    #include <vector>
    #include <numeric>
     
    int main(int argc, char* argv[])
    {
      if (argc <= 1) {
        std::cout << "Usage: " << argv[0] << " <a> <b> <c> ..." << std::endl;
        std::cout << "Example: " << argv[0] << " 1 2 3" << std::endl;
        return 0;
      }
     
      std::vector<int> numbers;
      for (int i = 1; i < argc; ++i) {
        int value;
        std::stringstream ss;
        ss << argv[I]; /* load the string representation into the stringstream */
        ss >> value; /* read it back out as an integer */
        if (ss.fail()) { /* detect parser errors */
          std::cout << "Error: Argument " << i << " is not an integer!" << std::endl;
          return 1;
        }
        numbers.push_back(value);
      }
     
      /* use the standard library to walk the array and sum the numbers */
      int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
      std::cout << sum << std::endl;
      return 0;
    }
    [/I]
     
    Last edited by a moderator: Dec 5, 2015
    Rip Cord and storm shadow like this.
Top