-1

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?

cigien
  • 57,834
  • 11
  • 73
  • 112
  • What is your question? – bitmask Oct 06 '20 at 01:28
  • The output should be `0000011` not the strange `?` character that appears at the end of the string. – Shantanu Tripathi Oct 06 '20 at 01:29
  • 1
    "4) Constructs the string with the first count characters of character string pointed to by s. s can contain null characters. The length of the string is count. The behavior is undefined if [s, s + count) is not a valid range." https://en.cppreference.com/w/cpp/string/basic_string/basic_string – JohnFilleau Oct 06 '20 at 01:34
  • @ShantanuTripathi That's not a question. That's a statement. And the statement is false. – eerorika Oct 06 '20 at 01:38

2 Answers2

2

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;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • what if someone want to append "11" two times? string(2, "12") does not work then. Is there any other option? – Shantanu Tripathi Oct 06 '20 at 01:42
  • @Shantanu `string(4, '1')` – JohnFilleau Oct 06 '20 at 01:43
  • @JohnFilleau in that case, using `string(one*2, '1')` would make more sense for this situation. – Remy Lebeau Oct 06 '20 at 01:46
  • @ShantanuTripathi There is no `string` constructor to duplicate a multi-character string N times, only a single `char` N times. You can use that constructor the way John shows, or you can use a manual loop instead, eg: `for(int i = 0; i < one; ++i) { ans += "11"; }` – Remy Lebeau Oct 06 '20 at 01:52
-1

Just use c++ strings and use + operator to catenate strings.

DS__ggg
  • 13
  • 4
  • 1
    Pretty sure that's what the asker is trying to do with `string("1", one);`. They just got the arguments wrong. – user4581301 Oct 06 '20 at 01:42