isdigit()无法将char转换为int

时间:2017-10-07 19:59:00

标签: c++ debugging

你好我是C ++的新手,也许是编程中的一个大菜鸟。无论如何我遇到了一个错误,其中isdigit似乎没有将char转换为int。香港专业教育学院一直在使用argv的命令行参数,这是一个char,想要检查输入的是1到35之间的数字,因为我要使用输入的数字作为int并使用它来决定有多少个圆球到在SFML程序中生成即时生成。

#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;
        }

    }
  }
}

说明错误的内容:

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

2 个答案:

答案 0 :(得分:0)

如果要检查argv[1](字符串)中的每个字符是否为数字,您可以执行以下操作:

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;
    }
}

答案 1 :(得分:0)

问题是您尝试在isdigit()上拨打char *,而期望char

isdigit(argv[1])更改为isdigit(argv[1][0])以检查第二个参数中的第一个字符是否为字符。但是,请注意,这只会检查第一个字符。如果您想支持两位数的数字,请同时检查isdigit(argv[1][1])

更好的解决方案

由于您使用的是CPP,因此您可以&amp;应该使用istringstreams进行转换,如下所示:

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...
}
相关问题