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.

3

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, from your experience which method is faster? to use % or since the input is continues to use counters (until 3 and 5)?