Thread: Input stream

  1. #1
    new
    Guest

    Input stream

    Hey everyone, how do I make it so when a user enters a string or character when the program is waiting for an integer the program doesn't flip out? I currently have something like:
    Code:
    while (n!=-1)
    {
       cin>>n;
    }
    but the program crashes when a letter or string is entered.

  2. #2
    Lead Moderator kermi3's Avatar
    Join Date
    Aug 1998
    Posts
    2,595
    what is n's decleration?
    Kermi3

    If you're new to the boards, welcome and reading this will help you get started.
    Information on code tags may be found here

    - Sandlot is the highest form of sport.

  3. #3
    new
    Guest
    It's declared as an int

  4. #4
    Evil Member
    Join Date
    Jan 2002
    Posts
    638
    If cin cannot translate what it finds into the appropriate variable, it enters a fail state. You can check for this. Here is some example code:

    Code:
    #include <iostream>
    
    #define expletive "moron"
    
    using namespace std;
    
    int main () {
    
      int n;
    
      bool nisgood = false;
    
      while (!nisgood) {
    
        cin >> n;
    
        if (cin.fail()) {
    
          cout << "That was supposed to be a NUMBER, " << expletive << ", now try again";
    
          //fflush(stdin); // Heh just kidding
    
          while (getchar() != '\n') {}
    
          cin.clear();
    
        } else nisgood = true;
    
      }
    
      return 0;
    
    }
    You can of course make this more elegant by tidying the error checking method into a tighter loop.
    Last edited by Imperito; 11-12-2002 at 08:18 PM.

  5. #5
    Registered User moi's Avatar
    Join Date
    Jul 2002
    Posts
    946
    forgot quotes around moron
    hello, internet!

  6. #6
    Evil Member
    Join Date
    Jan 2002
    Posts
    638
    D'oh.

    It wasn't "moron" when I typed it. Thats the beauty of macros...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. For loop problems, input please.
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-22-2007, 03:54 AM
  3. Ignoring puncuations in input stream
    By Muzzleloader in forum C++ Programming
    Replies: 8
    Last Post: 03-31-2007, 01:43 PM
  4. I would love some input on my BST tree.
    By StevenGarcia in forum C++ Programming
    Replies: 4
    Last Post: 01-15-2007, 01:22 AM
  5. Getting an input stream to stop creating a file
    By Stevek in forum C++ Programming
    Replies: 3
    Last Post: 03-21-2003, 04:45 PM