谢谢你们回答我的第一个问题,但我还有另一个问题。我这里有这个代码 使用strtol()函数。它有效,但问题是如果我输入三个选项之一:(d 2)它被认为是一个字符串,如果输入(2d)它是一个字符串,而(d2)是一个字符串。有没有办法检测数组中的数字?
char userInput[256];
char *end;
printf("Please enter your name: ");
scanf("%s", userInput);
int userName = strtol(userInput, &end, 10);
if (!*end)
{
printf("You have enter an int");
}
else
{
printf("You have entered a string");
}
答案 0 :(得分:1)
如果你真的需要检查字符串中是否有数字,那么这样做:
int has_ints(char * str) {
const int len = strlen(str);
int i;
for (i = 0; i < len; i++) {
if (str[i] <= '9' && str[i] >= '0') {
return 1;
}
}
return 0;
}
答案 1 :(得分:0)
我这样做:)工作得相当漂亮!
int exit = 0;
int i;
while (exit != 1)
{
char userInput[256] = {0};
int asciiCode[256];
int zeroCounter = 0;
int letterProof = 0;
int numberProof = 0;
int specicalCharactersProof = 0;
printf("\nPlease enter your name: ");
fgets(userInput, 256, stdin);
for (i = 0; i < 256; i++)
{
asciiCode[i] = userInput[i];
if (asciiCode[i] == 0)
{
zeroCounter++;
}
}
int reSize = (256 - zeroCounter);
for (i = 0; i < reSize; i++)
{
if (asciiCode[i] >= '0' && asciiCode[i] <= '9')
{
numberProof = 1;
}
else if ((asciiCode[i] >= 'a' && asciiCode[i] <= 'z') || (asciiCode[i] >= 'A' && asciiCode[i] <= 'Z'))
{
letterProof = 1;
}
else if ((asciiCode[i] >= '!' && asciiCode[i] <= '/') || (asciiCode[i] >= ':' && asciiCode[i] <= '@') || (asciiCode[i] >= '[' && asciiCode[i] <= '`') || (asciiCode[i] >= '{' && asciiCode[i] <= '~'))
{
specicalCharactersProof = 3;
}
}
if (letterProof == 1 && numberProof == 0 && specicalCharactersProof == 0)
{
printf("\nWelcome %s\n", userInput);
exit = 1;
}
else
{
printf("\nInvalid Input.\n");
}
}
return(0);
}