Hello, I'm new here and you'll be hearing from me a lot! Ive recently gotten into C++ and I decided to make a program to add two fractions. But what Ive gotten setup only accepts input like "1 2 3 4", but I want it to accept "1/2 3/4", how would I go about doing it?
Do you want it to accept both "1 2 3 4" and "1/2 3/4" or just the latter?
If just the latter, basically just provide a dummy variable to discard the slashes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Example program
#include <iostream>
int main()
{
int a;
int b;
int c;
int d;
char temp_slash;
std::cin >> a >> temp_slash >> b >> c >> temp_slash >> d;
std::cout << "you entered: " << a << "/" << b << " " << c << "/" << d << std::endl;
}
@Ganado Thank you! Is having a fake variable the only way? It seems a bit unprofessional. I'm more focused on writing good code than code that barely works. Not that youre version is bad, I'm just curious of there is a more professional way.
Yeah, I understand. But I can't think of a better way for something so simple, which I think the issue here, because the slash doesn't actually provide any function in your program. It's simply there as part of your required syntax.
You could do a safety check to make sure the character put into temp_clash is actually a slash, but other than that, I'm not sure what else there really is to do.
Kinda requires knowing what direction you want to take the program in. If you allowed more than one type of operator (ex: "3/4 5*6") then the slash would no longer be useless, because you'd actually be using it as part of the logic to determine whether you should divide or multiply, for example.
IMO, it makes more sense to set the stream's failure state rather than throwing an exception from the formatted input function. This makes the function's behavior consistent with the built-in ones, which obey the stream's exception mask.
1 2 3 4 5 6 7
std::istream& operator>>(std::istream& is, Fraction& frac)
{
char slash;
is >> frac.numerator >> slash >> frac.denominator;
if (is && slash != '/') is.setstate(std::ios::failbit);return is;
}