Tutorial Conversion of int to string

dila

New member
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:
#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 :)
 

dila

New member
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:
#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:
Top