在字符中查找数字
Findinga number in char
C语言如何查看用户提供的char中是否有数字?
要更改的最后一行 C 代码:):
char name;
do{
printf("What's your name?\n");
scanf("%s\n", name);
}
\and here's my pseudocode:
while (name consist of a sign (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9));
您需要包含 ctype.h
并使用 isdigit()
函数。
但是您在发布的代码中还有另一个问题,"%s"
说明符需要一个 char
指针,而您传递的是 char
,可能您需要的是 char
这样的数组
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[100];
int i;
do {
printf("What's your name?\n");
scanf("%s\n", name);
}
/* and here's my pseudocode: */
i = 0;
while ((name[i] != '[=10=]') &&
((isdigit(name[i]) != 0) || (name[i] == '-') || (name[i] == '+')))
{
/* do something here */
}
}
记得包括 ctype.h
和 stdio.h
使用isdigit();
原型为:
int isdigit(int c);
同样检查字符是字母
使用
isalpha()
这是在一次函数调用中测试指定字符的另一种方法。
#include <stdio.h>
#include <string.h>
int main()
{
char name[100];
char charset[]= "-+0123456789";
int len;
do {
printf("What's your name?\n");
scanf("%s", name);
len = strlen(name);
}
while (strcspn(name, charset) != len);
printf ("Your name is '%s'\n", name);
return 0;
}
从用户那里得到字符串后,循环搜索正确的输入。 (即查看字母字符集合中是否嵌入了数字)。这样的事情会起作用:
假设 userInput
是您的字符串:
int i, IsADigit=0;
int len = strlen(userInput);
for(i=0;i<len;i++)
{
IsADigit |= isdigit(userInput[i]);
}
循环中的表达式使用 |=
,如果字符串中的任何字符是数字,它将检测并保留 TRUE 值。
还有许多其他方法可以使用。
以及以下字符测试家族 将允许您对其他类型的搜索等进行类似的搜索:
isalnum(.) //alphanumeric test
isalpha(.) //alphabetic test
iscntrl(.) //control char test
isalnum(.) //decimal digit char test
isxdigit(.) //hex digit char test
islower(.) //lowercase char test
C语言如何查看用户提供的char中是否有数字? 要更改的最后一行 C 代码:):
char name;
do{
printf("What's your name?\n");
scanf("%s\n", name);
}
\and here's my pseudocode:
while (name consist of a sign (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9));
您需要包含 ctype.h
并使用 isdigit()
函数。
但是您在发布的代码中还有另一个问题,"%s"
说明符需要一个 char
指针,而您传递的是 char
,可能您需要的是 char
这样的数组
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[100];
int i;
do {
printf("What's your name?\n");
scanf("%s\n", name);
}
/* and here's my pseudocode: */
i = 0;
while ((name[i] != '[=10=]') &&
((isdigit(name[i]) != 0) || (name[i] == '-') || (name[i] == '+')))
{
/* do something here */
}
}
记得包括 ctype.h
和 stdio.h
使用isdigit();
原型为:
int isdigit(int c);
同样检查字符是字母
使用
isalpha()
这是在一次函数调用中测试指定字符的另一种方法。
#include <stdio.h>
#include <string.h>
int main()
{
char name[100];
char charset[]= "-+0123456789";
int len;
do {
printf("What's your name?\n");
scanf("%s", name);
len = strlen(name);
}
while (strcspn(name, charset) != len);
printf ("Your name is '%s'\n", name);
return 0;
}
从用户那里得到字符串后,循环搜索正确的输入。 (即查看字母字符集合中是否嵌入了数字)。这样的事情会起作用:
假设 userInput
是您的字符串:
int i, IsADigit=0;
int len = strlen(userInput);
for(i=0;i<len;i++)
{
IsADigit |= isdigit(userInput[i]);
}
循环中的表达式使用 |=
,如果字符串中的任何字符是数字,它将检测并保留 TRUE 值。
还有许多其他方法可以使用。
以及以下字符测试家族 将允许您对其他类型的搜索等进行类似的搜索:
isalnum(.) //alphanumeric test
isalpha(.) //alphabetic test
iscntrl(.) //control char test
isalnum(.) //decimal digit char test
isxdigit(.) //hex digit char test
islower(.) //lowercase char test