Thread: Input stream

  1. #1

    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:
    while (n!=-1)
    but the program crashes when a letter or string is entered.

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

    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
    It's declared as an int

  4. #4
    Evil Member
    Join Date
    Jan 2002
    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:

    #include <iostream>
    #define expletive "moron"
    using namespace std;
    int main () {
      int n;
      bool nisgood = false;
      while (!nisgood) {
        cin >> n;
        if ( {
          cout << "That was supposed to be a NUMBER, " << expletive << ", now try again";
          //fflush(stdin); // Heh just kidding
          while (getchar() != '\n') {}
        } 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 07:18 PM.

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

  6. #6
    Evil Member
    Join Date
    Jan 2002

    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, 12: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, 03:45 PM
Website Security Test