0

Here str2 is a string I need to append and str1 is the string I append onto str2. After I append last to str2 I need to append a number (int cnt) to str2. So I am using the below code, which came to my mind and it is working. Is it wrong to code like this, since I saw the usage of string s = lexical_cast<string>(a); and itoa (i,buffer,10); implementations where compiler complaints about the library.

    string str2;
    string str1;
    int cnt;
    str2 += str1 ;
    str2 += char(cnt+48);//cnt converted to ASCII char and appended;
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
ajax_velu
  • 286
  • 3
  • 16

2 Answers2

5

This statement

str2 += char(cnt+48);

is bad. Firstly it uses magic number 48. It would be better to write at least as

str2 += char( cnt + '0' );

Secondly the code will work only if cnt contains a number with one digit.

It would be better to use standard function std::to_string For example

str2 += std::to_string( cnt );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

If you don't want to use c++11 and its std::to_string(...) you can use ostringstream class.

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    ostringstream ss;

    ss << 1;

    string str = ss.str();

    cout << str << endl;

    return 0;
}

Output:

1
Dakorn
  • 883
  • 6
  • 11