gpt4 book ai didi

c++ - isdigit() 无法将 char 转换为 int

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:05 25 4
gpt4 key购买 nike

您好,我是 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;
}

}
}
}

这是错误的内容:

错误 C2664:“int isdigit(int)”:无法将参数 1 从“char *”转换为“int”

最佳答案

如果你想检查 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;
}
}

关于c++ - isdigit() 无法将 char 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46624542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com