While programming, we often need to convert an integer into string and vice-versa. Some of the examples scenarios to do so are as follows:
- One may want to concatenate a string and integer number
- Read input from a file that contains multiple integers and report the sum.
There are multiple ways to do it. C provides inbuilt functions stoi (read as string to integer) and sprintf to do this task. C++ provides an object-oriented approach for the same. It provides better methods to do it via sstream library.
Concatenation of a string and an integer: The following piece of code concatenates a string and an integer and returns the result as a string. It first declares an object of class stringstream and simply reads in a number into the object. There is nothing special that we need to do for the same.
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
string concatenate(const string &str,int num) {
stringstream s; // stringstream class is defined in sstream
s<<num; //integer num is assigned to string s
string ret = str + s.str(); // s.str() return string object from s
return ret;
}
String to integer conversion: Following piece of code (function) takes two strings as input, converts them into integers by assigning to objects of istringstream type, and returns their sum.
int sum(const string &str1,const string &str2) { istringstream s1(str1); // istringstream is defined in sstream istringstream s2(str2); int in1,in2; s1>>in1; s2>>in2; return in1+in2;}The following piece of code calls the above two functions to perform concatenation and calculations:
int main() { cout << concatenate("my birthday is on this month of ", 25)<<endl; cout<<"sum = "<<sum("1","2")<<endl; cout << concatenate("sum is ",sum("1","2") );}
Also read:
No comments:
Post a Comment
Thanks for your valuable inputs/feedbacks. :-)