I am typing a program in c++ where it takes a number and does the following.
If the number is a multiple of 3 but not 5, the output is Fizz.
If the number is a multiple of 5 but not 3, the output is Buzz.
If the number is a multiple of both 5 and 3, the output is FizzBuzz.
If the number is neither a multiple of 3 or 5, it just prints out the a number.
Whenever I compile the code with 15 as the test input, instead of getting the expected output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
I instead get this
FizzBuzz
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
My code is as follows:
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
void fizzBuzz(int n) {
for(int i = 0; i <= n; i++)
{
if(i % 3 == 0 && i % 5 != 0)
{
cout << "Fizz" << endl;
}
if (i % 3 != 0 && i % 5 == 0)
{
cout << "Buzz" << endl;
}
if (i % 3 != 0 && i % 5 != 0)
{
cout << i << endl;
}
if (i % 3 == 0 && i % 5 == 0)
{
cout << "FizzBuzz" << endl;
}
}
}
int main()
{
string n_temp;
getline(cin, n_temp);
int n = stoi(ltrim(rtrim(n_temp)));
fizzBuzz(n);
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
Would like to know what I'm doing wrong that's making the extra line in the output show up, any advice will be greatly appreciated!