geostocker geostocker - 1 year ago 72
C++ Question

String not modified by loop

I'm solving the following problem:

The assignment is to create and return a

object that consists of digits in an
that is sent in through the function's parameter; so the expected output of the function call
string pattern(int n)
would be

In case you're interested, here is the URL (You need to be signed in to view) to the full assignment, a CodeWars Kata

This is one of the tests (with my return included):

Test-case input: pattern(2)




Actual: "OUTPUT"

//string header file and namespace are already included for you
string pattern(int n){
string out = "OUTPUT";
for (int i = 1; i <= n; ++i){
string temp = "";
temp.insert(0, i, i);
out += temp;
return out;

The code is self-explanatory and I'm sure there are multiple ways of making it run quicker and more efficiently.

My question is two-fold. Why doesn't my loop start (even though my expression should hold true (1 <= 2) for above case)?

And how does my code hold in the grand scheme of things? Am I breaking any best-practices?

Answer Source

The overload of std::string::insert() that you are using takes three arguments:

  • index
  • count
  • character

You are using i as both count and character. However, the function expects the character to be of char type. In your case, your i is interpreted as a character with the code of 1 and 2, which are basically spaces (well, not really, but whatever). So your output really looks like OUTPUT___ where ___ are three spaces.

If you look at the ascii table, you will notice that digits 0123...9 have indexes from 48 to 57, so to get an index of a particular number, you can do i + 48, or i + '0' (where '0' is the index of 0, which is 48). Finally, you can do it all in the constructor:

string temp(i, i + '0');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download