开发者

using peek() in overloading an input stream

开发者 https://www.devze.com 2023-04-10 04:23 出处:网络
I\'m working on overloading >> for a fraction class and there are a few different types of input that need to be handled.Examples: 1/2 (regular fraction), 2+3/4开发者_运维问答 (mixed number), 2 (whole

I'm working on overloading >> for a fraction class and there are a few different types of input that need to be handled. Examples: 1/2 (regular fraction), 2+3/4开发者_运维问答 (mixed number), 2 (whole number). The professor provided a hint below saying that we need to use the peek() function in order to figure out what the second character is after the integer. So what that means is that temp needs to be declared as an int right? My question is that if temp is an int, how do you get the rest of the fraction (when it's not a whole number)?

Based on my experience, I would declare temp as a string instead and not use peek. But the int and peek approach must have some merit since the prof suggested it.

in >> temp;
if (in.peek() == '+'){
    doSomething...
} else if (in.peek() == '/'){
    doSomethingElse...
} else {
    doThirdOption
}


Here, when you use in>>temp , it will get all the numbers till some non numeric character is encountered. At this time, using peek() you can check if the next character is a '+' or a '/'.
In either case, you will have to read another number from the input stream and repeat this procedure.
Once the user hits enter, then you have all your numbers, and you can perform the required operations.

Also, if you have to calculate the value of fractions, you might be better off using float or double datatypes instead of int.

0

精彩评论

暂无评论...
验证码 换一张
取 消