How to check for invalid input?

I have no idea how to check if the input is valid or not. So please help and thanks in advance

I was asked to write a program that takes two numbers from the command line and adds them. The program should perform some basic error checking. The program should NOT ask for user input from the keyboard once it is running, all data should be entered on the command line once and the result should be displayed on the command line.If any operands are not valid decimal numbers the output shall be 'X'. NB: 1.3 is valid, ABC123 is not valid, 1.3.4 is not valid, 123abc is not valid.

This is what i have so far

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <errno.h> // not really needed, but keep it here, just in case.

using namespace std;

const double MAXRANGE = 32000;
const double MINRANGE = -32000;

int main(int argc, char *argv[])

if(argc == 2||argc > 3) //if 2 parameter or more than 3 parameter show P (ERROR CHECK 1)
cout << "P" << endl;

if(atoi(argv[1]) > MAXRANGE || atoi(argv[1]) < MINRANGE || atoi(argv[2]) > MAXRANGE || atoi(argv[2]) < MINRANGE) //(ERROR CHECK 3)
cout << "R" << endl;

int num1,num2,answer;
num1 = atoi(argv[1]);
num2 = atoi(argv[2]);
answer = num1+num2;

cout << "The answer is: " << answer << endl;

return 0;
You could write a character-by-character validation of the input strings, but you will be re-inventing code which already exists in standard library functions.

Your existing code uses type int but the numbers that are to be handled may contain a decimal part e.g. 1.3 so you should use type double instead.

One way would be to use a stringsteam. Initialise this with one of the parameters and then use the normal extraction operator >> to get the double value.

If the input was not valid, then either a) the operation will fail, or b) the stringstream will not be empty after the operation. You can check whether it is empty by attempting to extract a string (this should fail).

Another way to check the outcome of the stringstream operation would be to use the tellg(); function to find the position in the stream afterwards. This should be the same as the length of the string strlen(argv[1])

Last edited on
Topic archived. No new replies allowed.