FizzBuzz

Hi,

I normally use the FizzBuzz test and try to see how many different variations I can do to get used to a language when first starting. I've successfully made one FizzBuzz program but I'm struggling with this alteration. Can you have a look at the below and let me know if I'm doing anything majorly wrong?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main(){
 for (int i = 0; i < 101; i++){
  string output;
  output = "";

  if ( i % 5 == 0 ){ output += "Fizz"; }
  if ( i % 3 == 0 ){ output += "Buzz"; }
  if ( output == "" ){ output = i }

  cout << output << "\n";
 }
}


When I compile and run, I get a bunch of random output amongst the FizzBuzz output. Including normal characters and even "[" characters.

Hope this is enough information :)

Kind regards,
Mark Harwood
Well, what you posted doesn't compile.

But assuming it's a small typo and you simply forgot to put the semi-colon in line 11:

The issue is you're doing output = i;
This isn't doing what you think it's doing. When you assign an integer to a string, it is interpreting that number as an ASCII value, and converting the integer into a character.
For example, 64 is the @ symbol.
http://www.asciitable.com/

I would just do this instead:
1
2
3
4
5
6
  if ( output == "" ) {
    cout << i << "\n";
  }
  else {
    cout << output << "\n";
  }


Also, make sure you #include <string> when you work with strings.

PS: An alternative to the above is to use C++11's to_string.
1
2
3
4
5
6
7
8
9
10
11
  if ( i % 5 == 0 ) {
      output += "Fizz";
  }
  if ( i % 3 == 0 ) {
      output += "Buzz";
  }
  if ( output == "" )
  {
      output = std::to_string(i);
  }
  cout << output << "\n";
Last edited on
Thank you very much Ganado for your quick response! :)

Yep, that was just a typo from when I copied the program from my terminal.

I never even thought about C++ interpreting it as ASCII characters, that info might come in useful for other things further on down the line.

I have implemented your suggested "std::to+string()" fix and everything works fine now. Thank you again and have a very good new year.
Topic archived. No new replies allowed.