0

I am new to C++ and wrote the following:

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> result(n);
        for (int i=1;i<=n;++i)
        {
            if (i%3==0 and i%5==0)
                result[i-1]="FizzBuzz";
            else if (i%3==0)
                result[i-1]="Fizz";
            else if (i%5==0)
                result[i-1]="Buzz";
            else result[i-1]=""+i;
        }
        return result;
    }
};

when the input is 1 I am getting overflow error, why is that? the last line seems the problem but I think it's totally fine.

  • think about what it means to ""+i; where i is an int. After you think about it, give https://stackoverflow.com/questions/4668760/converting-an-int-to-stdstring a look? – Abel Feb 20 '21 at 23:52
  • Does this answer your question? [C++ character concatenation with std::string behavior. Please explain this](https://stackoverflow.com/questions/38573571/c-character-concatenation-with-stdstring-behavior-please-explain-this) – JaMiT Feb 21 '21 at 00:10
  • This is not an "Stack" overflow. – kdcode Feb 21 '21 at 05:38

1 Answers1

1

The expression ""+i doesn't convert the integer value in i to a string. Instead it's the same as &(("")[i]). I.e. it's a pointer to the i:th value of the string "". Which is out of bounds since the empty string only have a single element at index 0 (the string terminator).

Use std::to_string instead:

result[i-1]=std::to_string(i);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks, from your experience which method is faster? to use % or since the input is continues to use counters (until 3 and 5)? –  Feb 20 '21 at 23:58