September 20th, 2003, 01:03 PM
C++ input is "45 / 60" how do I ...
Hello all, Nice forum here.
How do I take a user input of
45 / 60 (forty five devided by sixty)
and seperate the numerator and denominator.
Example. I want the be able to call the numerater or the denomenator at a later time, but have to accept all of the input at the same time from the user. Thanks, Chuck
September 20th, 2003, 07:10 PM
You have to accept the input from the user as a string. Then parse the string into two smaller strings, knowing that they are separated by the / symbol (you could probably do some error checking here, to ensure there is a / symbol). Then call a function to convert a string to an integer for both of these strings, and you'll have your numbers.
September 20th, 2003, 08:20 PM
Thanks for the reply. I found the answer in the text....it is quite simple actually!
cout << "Enter a fraction" ; // fraction of the form " 89 / 10 "
cin >> x >> z >> y
cout looks like this 89/10
Thanks again! Chuck
September 23rd, 2003, 09:11 AM
I would assume that the code only works when there are spaces between the numbers and the division symbol (please correct me, if I am wrong). Even though I did notice the spaces in your thread title, I assumed that you placed them there for readability... I did not realize that this was a requirement of the input. In a real program, you should never assume anything from the user. It would be a good challenge for you to attempt to make the program work when there are no spaces, or even print an error message when there is no division symbol.