Thread: cin failure

  1. #1
    Registered User trekker's Avatar
    Join Date
    Mar 2002
    Posts
    46

    cin failure

    Code:
    ...
    int choice;
    cin >> choice;
    ...
    if i enter no numerical chars a cin error occurs
    that i can't restore with cin.clear()
    i detect the error with cin.fail()

    is it a fatal error?

    TIA
    to boldy code where...

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Try something like this one:
    Code:
    #include <iostream> 
    
    int main()
    {
      int i;
      
      std::cout <<"Enter a number" <<std::endl;
      while (!(std::cin>>i))
      {
        std::cout <<"Again:" <<std::endl;
        std::cin.clear();
        while (std::cin.get() != '\n');
      }
    
      std::cout <<"You entered " <<i <<std::endl;
    
    }
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Rad gcn_zelda's Avatar
    Join Date
    Mar 2003
    Posts
    942
    or take out all the std:: and put
    Code:
     using namespace std;
    at the begining

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    .. and for those interested, you can learn a little more about namespaces here
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File I/O Assertion Failure in VS2008
    By clegs in forum C Programming
    Replies: 5
    Last Post: 12-25-2008, 04:47 AM
  2. Integer Emulation
    By Elysia in forum C++ Programming
    Replies: 31
    Last Post: 03-18-2008, 01:03 PM
  3. cin problem
    By mikahell in forum C++ Programming
    Replies: 12
    Last Post: 08-22-2006, 11:14 AM
  4. getline(function)??
    By dac in forum C++ Programming
    Replies: 7
    Last Post: 03-10-2006, 12:42 PM
  5. cin not allowing input after first use of function
    By Peter5897 in forum C++ Programming
    Replies: 5
    Last Post: 01-31-2006, 06:29 PM