Hi all im after a piece of code that allows the user to enter a fraction e.g 1/4 and have the code split that fraction into 2 seperate variables, e.g
variable 1 containing the '1'
variable 2 cantaining the '4'

How would i achive this?

My objective is to make a calculator for horse racing that will work out the payout for your horse, any ideas?

Take it into a string and parse everything (either with your own function that multiplies out the place values or something like atoi) up to the slash as one integer and parse everything after as a second integer.

Or a simple way to do it would be have the user input the numerator, print out a slash and have them put in the denominator.

Well instead of asking the user to input a fraction as a string you could instead ask the user to actually put 2 integers and 1 character so it would be something like this.

#include <iostream>

using namespace std;

int main()
{
	int num1, num2:
	char slash;

	cin >> num1 >> slash >> num2;

	cout << "Fraction: " << num1 << "/" << num2;

	return 0:
}

Or you could ask for a string and then get the string length then make a for loop that would save every number before the slash and after the slash to an extern string and then convert it to an integer.

Anyways this are my 2 ways of solving it, there might be more and better ones out there but I only know this ones :). Hope it helped.

This way achieving the function is more simple and easy to understand

#include <iostream>
using namespace std;

int main()
{
    int linum1 = 0, linum2 = 0;
    char fraction[16] = {'\0'};

   cin>>fraction;
   if(sscanf(fraction, "%d/%d", &linum1, &linun2) < 2)
      cout<<"input error !!"<<endl;

   return 0;
}
commented: excelent post +1

thank you chary8088,

worked fine did that code,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.