The following program expects user input in the mixed fraction format ‘whole_numbernumerator/denominator’ and assigns values to respective variables.
#include<iostream>
using namespace std;
int main()
{
int whole, numerator, denominator;
cout << "Input format: i<space>n/d" << endl;
cin >> whole;
cin.ignore(1000, ' ');
cin >> numerator;
cin.ignore(1000, '/');
cin >> denominator;
cout << whole << endl;
cout << numerator << endl;
cout << denominator << endl;
return 0;
}
Input1:
123 345/678
Output1:
123
345
678
Input2:
1111111111 1111111111/1111111111
Output2:
1111111111
1111111111
1111111111
Input3:
2222222222 2222222222/222222222
Output3:
2147483647
0
0
I haven’t been able to figure out why the program doesn’t work for Input3.
You’re overflowing the maximum value for a 32-bit integer (2^31-1 ~= 2.147b). Once this happens,
cindoesn’t work properly until you clear the flag. You should be checking for errors, but a short-term solution is to make your number unsigned, or use a 64-bit one, likeint64_t. You also don’t need to ignore the space, ascinwill skip it by default.You can implement something like what’s found here to ensure valid input, but it needs to be tailored to fit your specific input format. Perhaps encapsulating the three into a single type with an overloaded operator that inputs each with respect to the formatting would make the syntax fit more nicely, so you could replace
agein the example with aMixedNumberobject.I would see something like this as a versatile method:
Then you could just have your program as follows: