Thread: how to allow user to input only integer?

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    2

    how to allow user to input only integer?

    hello,

    my programm must allow user to enter only integer values, if user enters char or string programm gives him a warning and asks to enter value again..
    its nothing hard but i am missing here something..

    ill write u what i have tried so ull better understand the problem and i hope u guys can help me

    Code:
    #include <iostream>
    #include <iomanip.h>
    #include <sstream>
    
    using namespace std;
    int main()
    
    {
    string mystr;
    int number=0;
    
    cout<<"please enter a number!"<<endl;
    cin>>mystr;
    
    stringstream(mystr) >> number; //converting string to int
    if(number==0)
    cout<<"U've entered not an integer!!"<<endl;
    
    <and the rest of the code>
    
    return 0;
    }
    if i enter character then function stringstream(mystr) returns 0 and all is great but if i enter 0 program doesnt understand that its a number and sends it to if(number==0) structure and i get message "U've entered not an integer!!"

    i could solve the problem if i used char instead of str, but char can contain only one character so with 2 or more digit numbers it isnt working..

    can You guys tell me how can i be able to enter only integer values?

    Thx You a lot!


    p.s. One smart guy told me how to solve this, thx anyways
    Last edited by errtime; 09-20-2007 at 11:50 PM. Reason: solved the problem

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You need to check the return value of the stream when it tries to convert to the number. You can do this with the stringstream or directly with cin. For example, to do it with cin you could do:
    Code:
    while (!(cin >> number))
    {
        cin.clear(); // clear failbit from character
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore bad input
        cout<<"U've entered not an integer!!"<<endl;
    }
    You should #include <limits> and #include <ios> for the stuff in the ignore line, or you can just use cin.ignore(1000, '\n');.

    If you wanted to use the stringstream version, you would do basically the same thing. Check the state of the stream after it tries to convert to an int.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  2. Replies: 4
    Last Post: 04-21-2004, 04:18 PM
  3. Validate a user input integer?
    By criticalerror in forum C++ Programming
    Replies: 20
    Last Post: 12-07-2003, 08:30 PM
  4. ~ User Input script help~
    By indy in forum C Programming
    Replies: 4
    Last Post: 12-02-2003, 06:01 AM
  5. Error checking user input
    By theharbinger in forum C++ Programming
    Replies: 5
    Last Post: 07-22-2003, 09:57 AM