Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8464299
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T14:42:15+00:00 2026-06-10T14:42:15+00:00

std::istream & operator >>(std::istream & ins, Rational & target) { int num, den; char

  • 0
std::istream & operator >>(std::istream & ins, Rational & target)
{
    int num, den;
    char symb;          
    std::cout << "Please enter a rational number: ";
    ins >> num >> symb >> den;
    std::cout << std::endl;

    if(validateInput(num, symb, den)){
        target = Rational(num, den);            
        return ins;
    }
    else{
        std::cin >> target;
    }
}

bool validateInput(int num, char symb, int den)
{
    if(symb != '/'){
        std::cout << "Error: Illegal format. Please use '2/4'." << std::endl;
        return false;
    }
    if((static_cast<int>(num) != num) && (static_cast<int>(den) != den)){
        std::cout << "Error: Not a valid rational number." << std::endl;
        return false;
    }
    if(den == 0){
        std::cout << "Error: Cannot divide by 0." << std::endl;
        return false;
    }

    return true;
}

It’s taking in a rational number in the format ‘x/y’, so 2/4 for instance.
It works fine if I type it right. If I type in 2p4, it will give the correct error (that I’m missing a ‘/’) and then ask for a new number. If 0 is in the denominator, it will also report the error and ask for a new number.

But checking to see if it’s a valid number doesn’t seem to work. If I type in ‘a/4’, it will just loop infinitely until it crashes. I can’t figure out why. Checking the debugger, it goes back to the ins >> statement, but doesn’t ask for anything from the user.

I’m assuming my logic is wrong somewhere. Note, I’m fairly new to C++, still learning. I was trying exception handling earlier, still haven’t learned it properly, so I settled back on something I’m more familiar with.

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T14:42:17+00:00Added an answer on June 10, 2026 at 2:42 pm

    The basic gist of the issue is that C++ streams formatted extraction operators stop working if the state of the stream goes bad, and you have to reset the state for them to work again.

    You have other issues, as well.

    First of all, your validation function reveals your lack of experience: static_cast<int>(intval) == intval will always be true and confirms nothing. Secondly, you fail to verify that you have indeed succeeded in extracting values from the stream (this is the cause for your infinite loop: all you do is fail the verification over and over again.)

    So, when you extract values, you should verify that all went alright, like this:

    int num, den;
    char symb;
    // Remember to flush unfinished lines
    std::cout << "Please enter a rational number: " << std::flush; 
    if (std::cin >> num >> symb >> den)
        // you extracted an integer, a character and an integer succesfully
        // perhaps check that the character is '/' and denominator is non-zero
    else
        // there was an error: what should we do?
    

    The “what should we do” part is far from obvious: you could just reset the stream and remove the first offending byte from it and try again, if you think that’s reasonable (and intuitive). However, the extraction may have also failed due to too large numbers, in which case this may lead odd behaviour: consider the following input (on an implementation with common long size):

    3111111111111111111111111111111111111111111111111/3
    

    If you haven’t got any actual specifications, a thing to consider would be line-orientated input: first read a line and try to parse it; if it doesn’t look OK, ignore it and try the next one.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to do the following: template <class T> std::ifstream& operator>> (std::ifstream& fin,
This is the C++ code: #include<iostream> using namespace std; int a=8; int fun(int &a)
Error: ..\Record.cpp: In function `std::ostream& operator<<(std::ostream&, Record&)': ..\Record.cpp:83: error: no match for 'operator<<' in
How can I read from an std::istream using operator>> ? I tried the following:
I have the following: using namespace std; template<class T> class olsm; template<class T> istream&
I'm using std::getline() to read lines from an std::istream-derived class, how can I move
Is there a better way to determine the length of an std::istream than the
This is from the <iostream> : namespace std { extern istream cin; ///< Linked
In my class File, I've: class File { std::vector<char> name, timeOfCreation, timeOfLastEdit, content; std::vector<char>::const_iterator*
std::ifstream sr(path.c_str()); if (!sr) throw runtime_error(Could not open file '+path+\'); sr.seekg(0, ios::end); streampos lastPos

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.