For my class I was asked to create some code to be able to accept input for 3 types of numbers: one that is divisible by 3, by 5, and by both 3 and 5. That all went fine using if else statements, but now I am having trouble expanding the program to accept multiple numbers separated by commas. I am thinking that this can be solved with strings but I am not sure how to set it up.
#include <iostream>
#include <cmath>
#include <string>
usingnamespace std;
int main()
{
int number;
cout << "Please input a number and press the enter key" << endl;
cin >> number;
if (number % 15 == 0){
cout << "FizzBuzz" << endl;/*FizzBuzz - do this one first as my `if` block is not mutually exclusive*/
}
elseif (number % 3 == 0){
cout << "Fizz" << endl;/*Fizz*/
}
elseif (number % 5 == 0){
cout << "Buzz" << endl;/*Buzz*/
}
else
cout << "Please Select a different number" << endl; /*The number entered is neither divisible by 3 or 5*/
return 0;
}
#include <iostream>
usingnamespace std;
int main() {
int number;
cout << "Please input a number and press the enter key" << endl;
cin >> number;
if (number % 5 == 0 && number % 3 == 0) {
cout << "FizzBuzz" << endl;/*FizzBuzz - do this one first as my `if` block is not mutually exclusive*/
}
elseif (number % 3 == 0) {
cout << "Fizz" << endl;/*Fizz*/
}
elseif (number % 5 == 0) {
cout << "Buzz" << endl;/*Buzz*/
}
else
cout << "Please Select a different number" << endl; /*The number entered is neither divisible by 3 or 5*/
return 0;
}
I am able to get the program to react accordingly for the first number entered, but lets say the user inputs 8,10,25. I would like the program to then output "8 - Please Select another number, 10 - Buzz, 25 - FizzBuzz."
As it stands if the user inputs just a 10 it will output "10 - Buzz". However, if you input multiple numbers it will still just output "10 - Buzz." I am looking for the proper output for each input. Does that make better sense?
#include<iostream>
#include<cstring>
#include <sstream>
int main()
{
constchar comma = ',' ;
std::cout << "enter a sequence of numbers separated by commas on a single line\n" ;
std::string line ;
std::getline( std::cin, line ) ; // read the complete line as a string
std::cout << "you entered: " << line << '\n' ;
line += comma ; // append a comma at the end; this will make our processing simpler
std::istringstream strstm(line) ; // construct a string stream which can read integers from the line
int number ;
char separator ;
while( strstm >> number >> separator && separator == comma ) // for each number read from the line
{
constbool divisible_by_3 = number%3 == 0 ;
constbool divisible_by_5 = number%5 == 0 ;
std::cout << number << " - " ;
if( divisible_by_3 && divisible_by_5 ) std::cout << "both a fizz and a buzz\n" ;
elseif( divisible_by_3 ) std::cout << "only a fizz\n" ;
elseif( divisible_by_5 ) std::cout << "only a buzz\n" ;
else std::cout << "no fizz and no buzz\n" ;
}
}