Thinking in C++

My C++ code snips.

Input bullet-proofing in C++

Posted by Abhi on June 8, 2012

Yes, it’s a lot of code for something that should be much simpler but it’s the only fool proof way I know off to make sure that the program accepts only integers.


#include <iostream>
#include <sstream>
#include <string>
#include <cctype>

int ReadInt(const std::string &prompt)
{
    std::stringstream strm;
    std::string s;
    int val;
    bool flag;
    while(std::cout<<prompt && std::getline(std::cin,s))
    {
        flag = true;
        for(std::string::size_type index = 0; index!= s.size(); ++index)
        {
            if(!isdigit(s[index]))			// isdigit() included in cctype
            {
                flag=false;
                std::cout<<"Invalid input; Please try again.\n";
                break;
            }
        }
        if(!flag)
            continue;
        break;
    }
    strm.str(s);	// Copying the string into the stream.
    strm>>val;		// reading the stream into an integer.
    return val;
}

Usage:


#include "readInt.h"
#include <iostream>

using std::cout;
using std::endl;

int main(int argc, char** argv) {

    int a=ReadInt("Please enter the value of a;");
    int b=ReadInt("Please enter the value of b;");
    cout<<a*b<<endl;

    return 0;
}

Example:


Please enter the value of a;5t
Invalid input; Please try again.
Please enter the value of a;sa sa sa
Invalid input; Please try again.
Please enter the value of a;55
Please enter the value of b;2
110

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: