Can't figure out how to detect zero when using command prompt inputs.

Hello,

I am a student who has just begun to learn how to use C++. For our first lab, we are required to write a program that adds two numbers using inputs from the Command Prompt or Parameters (in wxDevC++). The program includes a variety of error checks as shown in the code I have written:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <cstdlib>
#include <iostream>

using namespace std;

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

int main(int argc, char *argv[])
{
    double a,b;

    if (argc == 1)
    {
        cout << "student_number,student_email,student_name"<<"\n";
        system("Pause");
        return 0;
    }

    if ((argc == 2)||(argc > 3))
    {
        cout << "P" << "\n";
        system("Pause");
        return 0;
    }

    if (argc == 3)
    {
        a = atof(argv[1]);
        b = atof(argv[2]);

        if(a == 0 || b == 0)
        {
            cout << "X" << "\n";
            system("Pause");
            return 0;
        }

        if ((a > 32000 || b > 32000)||(a < -32000 || b < -32000))
        {
            cout << "R" << "\n";
            system("Pause");
            return 0;
        }

        cout << a + b << "\n";
        system("Pause");
        return 0;
    }
    return 0;
}


One of the error checks requires that the inputs are within the range of -32000 and +32000. If they are out of this range or the input is a zero ('0') then the program ouputs 'R'. However the program, as it is stands, cannot tell the difference between a '0' or non-numerical input since atof will only output inputs such as letters as zero. As a result, any instance of zero results in the program giving an ouput of 'X'. I tried finding ways for the program to check the strings in argv[1] and argv[2] before being checked by the other errors checks in the program but have been unable to do so. Does anyone have any suggestions?
Use strtod() rather than atof().

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdlib.h>

// double strtod( const char* nptr, char** endPtr );

int main( int argc, char* argv[] ) {
   //...
   char* endPtr = 0;
   double result = strtod( argv[2], &endPtr );
   if( *endPtr ) {
      cout << "X" << endl;
      // ...
   }
   // ... 


To be safe, you also need to check for overflow/underflow by checking errno.

(just man 3 strtod if using un*x)

Thanks jsmith, that helped a lot.
Is there a function similar to strtod() that will detect characters?
Topic archived. No new replies allowed.