geostocker geostocker - 22 days ago 6
C++ Question

String not modified by loop

I'm solving the following problem:

The assignment is to create and return a

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

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)

Expected:

1

22

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

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');