Reputation: 188
I want to get output some thing like this..
Word_1
Word_2
Word_3
.
.
.
Word_1234
etc...
I have seen sprintf
and itoa
etc to format string, to convert int to string. In case of sprintf
I have to declare size.
With "Word_"+itoa(iterator_variable)
, I think I can get what is needed. But is there any better way to get the desired output?
Upvotes: 0
Views: 94
Reputation: 378
I would recommend stringstreams, as they allow any strings, streams, and arithmetic types (among other things) to be concatenated into a character representation.
#include <sstream>
#include <iostream>
int main()
{
int n1 = 3;
int n2 = 99;
std::stringstream ss;
// all entries in the same stringstream
ss << "Word_" << n1 << std::endl;
ss << "Word_" << n2 << std::endl;
std::cout << ss.str();
// clear
ss.str("");
// entries in individual streams
std::string s1, s2;
ss << "Word_" << n1;
s1 = ss.str();
ss.str("");
ss << "Word_" << n2;
s2 = ss.str();
std::cout << s1 << std::endl << s2 << std::endl;
return 0;
}
Upvotes: 0
Reputation: 6088
If you have access to C++11 you could use std::to_string()
std::string s = "Word_";
std::string t = s + std::to_string( 1234 );
std::cout << t << std::endl;
Upvotes: 1
Reputation: 2624
Using c++ I like to use boost::format and boost::lexical_cast to solve these sort of problems.
Upvotes: 0