Jj Hagen Jj Hagen - 1 month ago 8
C++ Question

How to split a fraction into two integers c++

I'm working on an assignment. I need to have the user input a fraction in

#/#
format . How can I set the top and bottom to two separate variables?

Here's a chunk of code I've tried, but I keep getting nothing for the second variable:

#include <iostream>
#include <conio.h>
#include <cstdio>
#include <regex>

using namespace std;

int main() {
string firstFraction;

cout << "Enter your first real Fraction: " << endl;
firstFraction = cin.get();

string delimiter = "/";

string numerator = firstFraction.substr(0,firstFraction.find(delimiter));

size_t pos = firstFraction.find("/");
string denominator = firstFraction.substr(pos);

cout << numerator << " / " << denominator << endl;
_getch();
return 0;
}

Answer

Try something like this:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
    string fraction;

    cout << "Enter your first real Fraction: " << endl;
    getline(cin, fraction);

    istringstream iss(fraction);

    string numerator, denominator;
    getline(iss, numerator, '/');
    getline(iss, denominator);

    cout << numerator << " / " << denominator << endl;

    cin.get();
    return 0;
}
Comments