1

Hello im new to C++ and perhaps a big noob in programming in general. anyways ive encountered an error where isdigit doesnt seem to convert the char to int. ive been using a command-line argument of argv which is a char and want to check if what was typed was a number from 1 to 35 because im gonna use the inputted number to be an int and use it to dictate how many circle balls to spawn in an SFML program im to make.

#include <ctype.h>

using namespace std;

int main(int argc, char *argv[])
{
  if (argc > 2 || argc < 1)
  {
    cout << "Invalid Command!" << endl;
  }
  if (argc == 1)
  {
    cout << "Please input X number of circles from 1 to 35." << endl;
  }
  if (argc == 2)
  {
    if (isdigit(argv[1]))
    {
        int X = atoi(argv[1]);
        if (X >= 1 && X <= 35)
        {
            //do stuff
        }
        else
        {
            cout << "Please input X number of circles from 1 to 35." << endl;
        }

    }
  }
}

Heres what the error says:

error C2664: 'int isdigit(int)' : cannot convert argument 1 from 'char *' to 'int'

alseether
  • 1,889
  • 2
  • 24
  • 39
MLG Chan
  • 61
  • 4

2 Answers2

0

If you want to check whether each character in argv[1] (which is a string) is a digit, you could do the following:

bool isDigit = true;
for (int i = 0; argv[1][i]; i++)
{
    if (!isdigit(argv[1][i]))
    {
        isDigit = false;
        break;
    }
}

if (isDigit)
{
    int X = atoi(argv[1]);
    if (X >= 1 && X <= 35)
    {
        //do stuff
    }
    else
    {
        cout << "Please input X number of circles from 1 to 35." << endl;
    }
}
frslm
  • 2,969
  • 3
  • 13
  • 26
0

The problem is your are trying to call isdigit() on a char * whereas it expects a char.

Change isdigit(argv[1]) to isdigit(argv[1][0]) to check if the first character in the second argument is a character. But, beware, this will only check the first character. If you want to support two-digit numbers, you shoud check isdigit(argv[1][1]) as well.

Even better solution

Since you are using CPP, you could & should use istringstreams for your conversions like so:

int i;
std::istringstream ss(argv[1]);
ss >> i;
if (!ss.good()) {
  // Input was not a number...
} else if (i >= 1 && i <= 35) {
  // Use i...
} else {
  // I not in range...
}
Daniel Trugman
  • 8,186
  • 20
  • 41