0

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?

6
  • What is wrong with your second option "Word_"+itoa(i)? Commented Jul 7, 2014 at 12:04
  • If I remember correctly, in C++ you can just concatenate numbers to a string using the += operator. If you just want to output the strings and don't have to remember them, you can probably get away with printf("%s%d\n",string.c_str(),int); or cout << string << int << endl; Commented Jul 7, 2014 at 12:05
  • 1
    possible duplicate of Easiest way to convert int to string in C++ Commented Jul 7, 2014 at 12:05
  • @RevanProdigalKnight Yes, but you have to convert the int to a string first. Which is why OP used itoa Commented Jul 7, 2014 at 12:05
  • 1
    @RevanProdigalKnight: You don't remember correctly. Commented Jul 7, 2014 at 12:08

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

Using c++ I like to use boost::format and boost::lexical_cast to solve these sort of problems.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.