I am working on a school assignment and one part of it has me a little stuck. I need to have the user enter as many fractions as desired until a 0 is entered for the numerator, and save those fractions in a structure I created.
I was attempting to us strtok to split the c-string that I would use to store the user input by space and then by “/”, but I got very stuck and couldn’t get any proper output (the code below is main() it has a run time error and the second for loop would obviously fail in assigning anything proper to den).
What would be the simplest way in achieving this.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
struct Fraction
{
int num, den;
};
int main()
{
Fraction* fractions[100];
char s[100] ;
cout << "Enter fractions (end by entering a 0): ";
cin >> s;
const char* p;
int count = 0;
for (p = strtok( s, " " ); p; p = strtok( NULL, "," ))
{
const char* frac = p;
for (frac = strtok( s, " " ); frac; frac = strtok( NULL, "/" ))
{
fractions[count]->num = (int)frac;
count++;
}
}
return 0;
}
You don’t want
you just want
The first is an array of pointers to
Fractionss, the second is just an array ofFractions. The problem you are probably having is that you didn’t initialize the pointers.An even better approach might be to use a
std::vector<Fraction>to store yourFractions. Then, you can dynamically add to it, and it can store as manyFractions as you need.Another error you have is the way that you are reading in values. When you call
It won’t read in a full line, only a single token. Also, you’re only ever setting the numerator of your fractions. Thus, you have two options:
Use
getline, to read in a full line and then parse it from there.Just use
cin >>more effectively, and do something like:–