3

I wanted to test my C++ skills by hammering out a quick fizzbuzz application. The code for it is posted below. However, when I run this application, something crazy occurs. Here's my code:

#include <iostream>
#include <string>
using namespace std;

bool ismultiple3(int i) {
  int res = i%3;
  if (res == 0)
    return true;
  return false;
}

bool ismultiple5(int i) {
  int res = i%5;
  if (res == 0)
    return true;
  return false;
}

int main() {
  string output;
  for (int i = 1; i <= 100; i++) {
    output = i;
    if (ismultiple5(i) || ismultiple3(i)) {
      output = "";
      if (ismultiple3(i)) output.append("Fizz");
      if (ismultiple5(i)) output.append("Buzz");
    }
    cout << output;
  }
}

So when I run and compile it, my whole terminal gets messed up. It seems like the character encoding is somehow being altered. It still accepts commands normally, it just looks off. I ran an ls to demonstrate this. Compiled, ran, and ls Remainder of ls command

Edit: In case anyone runs across this, I ended up adding an else statement and doing cout << i in it, because my computer's g++ compiler lacked C++11 support. The functions were also shortened and combined into a single function that accepts 2 arguments, i and n.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Nathan
  • 2,093
  • 3
  • 20
  • 33

2 Answers2

3

As other commenters have said, output = i is the issue here. The value of i casts from an int to a char, leaving the output string with a sequence ASCII characters when you run that loop. For example, 97 == 'a', 144 == 'É', and so on.

I would consider rewriting the logic in the main function to simply have three cout << ... calls inside an if-else block. Additionally, the ismultipleN() functions can be replaced with simply (i % 3 == 0) for brevity.

Vortico
  • 2,610
  • 2
  • 32
  • 49
  • As I commented earlier, I expanded out my functions to make things clearer for myself. Thanks for the advice though. – Nathan Nov 16 '12 at 03:34
2

instead of

 output = i;

You should use one of the methods suggested in this answer.

For example:

std::string to_string(int x) {
    std::stringstream out;
    out << x;
    return out.str();
}
Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • I tried using to_string() but apparently my version of g++ doesn't have C++11 support. Yaaaay. Streams would require restructuring unless there's an uncomplicated way to flush streams (which is already too complicated for a fizzbuzz application). – Nathan Nov 16 '12 at 03:30
  • 1
    @derekwolf, see http://stackoverflow.com/a/13388063/5987. Otherwise you might need to enable C++11 with a command line switch. – Mark Ransom Nov 16 '12 at 03:33
  • @derekwolf: I've made a small edit to my post. You could easily take one of the examples in that post, and convert it into a function, such as I have. Then, instead of `output = i`, you should do `output = to_string(i)`. – Bill Lynch Nov 16 '12 at 04:40