Search code examples
c++stringstdstring

Strange behaviour while adding string to another string in C++


one is 2, and ans is "000000".

string ans = "000000";
ans += string("1", one);
cout<<ans<<endl;

The output is:

0000001�

But I want the output:

00000011

What am I doing wrong?


Solution

  • string("1", one) does not do what you think it does. It does not duplicate the "1" string one number of times. It instead copies the 1st one number of chars from "1", which in this case is the '1' character and the '\0' null-terminator that follows it, which is where the is coming from in the output. That is not what you want.

    Use string(one, '1') instead. That will duplicate the '1' character one number of times, like you want, eg:

    ans = "000000";
    ans += string(one, '1');
    cout << ans << endl;