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

  • Home
  • SEARCH
  • 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 531235
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T09:16:48+00:00 2026-05-13T09:16:48+00:00

When running the following code and enter a number, it works fine. But when

  • 0

When running the following code and enter a number, it works fine.
But when entering a letter, the program enters an infinite loop, displaying “Enter a number (0 to exit): cin failed.”

My intent was to handle the cin fail case and prompt the user again.

int number;
do{
    cout << "Enter a number (0 to exit): ";
    cin >> number;
    if(cin.fail()){
        cout << "cin failed." << endl;
        cin.clear();
    }else{
        cout << "cin succeeded, " << number << " entered." << endl;
    }
}while(number != 0);
  • 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-05-13T09:16:48+00:00Added an answer on May 13, 2026 at 9:16 am

    You need to clear the line from cin, using cin.ignore, in addition to clearing the stream state (which is what cin.clear does).

    I have several utility functions to make this easier (you’ll be interested in clearline in particular, which clears the stream state and the current line) and almost an exact example of what you want.

    Your code, more or less, using my clearline:

    #include "clinput.hpp" // move my file to a location it can be used from
    
    int main() {
      using namespace std;
      while (true) {
        cout << "Enter a number (0 to exit): ";
        int number;
        if (cin >> number) {
          cout << "Read " << number << '\n';
          if (number == 0) {
            break;
          }
        }
        else {
          if (cin.eof()) { // tested only *after* failed state
            cerr << "Input failed due to EOF, exiting.\n";
            return 1;
          }
          cerr << "Input failed, try again.\n";
          clearline(cin); // "cin >> clearline" is identical
        }
      }
      return 0;
    }
    

    There is still a potential issue here (fixed in my clinput_loop.cpp with blankline), with leaving input in the buffer that will screw up later IO (see “42 abc” in the sample session). Extracting the above code into a separate and self-contained function is left as an exercise for the reader, but here’s a skeleton:

    template<class Type, class Ch, class ChTr>
    Type read(std::basic_istream<Ch,ChTr>& stream, Ch const* prompt) {
      Type value;
      // *try input here*
      if (could_not_get_input or more_of_line_left) {
        throw std::runtime_error("...");
      }
      return value;
    }
    template<class Type, class Ch, class ChTr>
    void read_into(
      Type& value,
      std::basic_istream<Ch,ChTr>& stream,
      Ch const* prompt
    ) {
      value = read<Type>(stream, prompt);
    }
    

    Example use:

    int n;
    try {
      read_into(n, std::cin, "Enter a number: ");
    }
    catch (std::runtime_error& e) {
      //...
      raise;
    }
    cout << "Read " << n << '\n';
    

    clearline function extracted for posterity, in case above links ever break (and slightly changed to make self-contained):

    #include <istream>
    #include <limits>
    
    template<class C, class T>
    std::basic_istream<C,T>& clearline(std::basic_istream<C,T>& s) {
      s.clear();
      s.ignore(std::numeric_limits<std::streamsize>::max(), s.widen('\n'))
      return s;
    }
    

    The template stuff is a bit confusing if you’re not used to it, but it’s not hard:

    • std::istream is a typedef of std::basic_istream<char, std::char_traits<char> >
    • std::wistream is a typedef of std::basic_istream<wchar_t, std::char_traits<wchar_t> >
    • widen allows '\n' to become L'\n' as appropriate
    • this code works for both of the common char and wchar_t cases, but also any compatible instantiation of basic_istream
    • it’s written to be called as clearline(stream) or stream >> clearline, compare to other manipulators like std::endl, std::ws, or std::boolalpha
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 275k
  • Answers 275k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer There is certainly a dependency on the exact class. Remember… May 13, 2026 at 2:39 pm
  • Editorial Team
    Editorial Team added an answer You have : public Fordon(float weight) { // What is… May 13, 2026 at 2:39 pm
  • Editorial Team
    Editorial Team added an answer The language he uses is most likely Chez Scheme. Regardless,… May 13, 2026 at 2:39 pm

Related Questions

I have an existing web application that I am converting to use CakePHP. The
enter code here Hi All, I have a simple windows service application that connects
So i am trying to get a simple system working where i have an
I'm currently learning Python using Zelle's Introductory text, and I'm trying to recreate one
I made a Powershell function just now and saved it to a ps1 file.

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.