CodeWars C++ basic problem

So I’m fairly new to C++ and thought I’d have a go with solving some basic problems.
My solution so far

#include <string>
using namespace std;

string multi_table(int number)
{
  for(int i{1}; i < 11; i++){
    cout << i << " * " << number << " = " << number*i;
    if (i != 10){
      cout << endl;
    }
}
    return ""; 
}

It returns exactly what is expected although there’s still an error? The initial set up threw me off to begin with (the lack of “int main()”, and the returning of an empty string).

1 Like

I think the instructions want you to return a string with this output instead of sending it to cout. So you will need to build up a string and then return that string. Look at the sample tests:

do_test(5, "1 * 5 = 5\n2 * 5 = 10\n3 * 5 = 15\n4 * 5 = 20\n5 * 5 = 25\n6 * 5 = 30\n7 * 5 = 35\n8 * 5 = 40\n9 * 5 = 45\n10 * 5 = 50")

This is showing you what the string you return should look like if 5 is passed into the function.

2 Likes

Ahhhh ok, so return a single value rather? Instead of multiple console logs?

#include <string>
#include <iostream>

using namespace std;

string multi_table(int number){
      string result{""};
{

  for(int i{1}; i < 11; i++){
    result += to_string(i) + " * " + to_string(number) + " = " + to_string(number*i);
    if(i != 10)
        result += "\n";
    }
}
    return result; 
}

I’ve tried this and it passed thankfully. Do you know if there’s any simpler solution? Can I refactor this?

1 Like