我一直在努力完成一个项目,所以我必须验证C中的4位数,我想使用字符,因为我需要验证0001但没有1.然后我想我需要将其转换为整数使用它。有人能帮助我吗?
printf("Enter a number 0 to end:");
gets(str);
while (strcmp(str, "0"))
{
j = 0;
k = 0;
flag = 0;
while (*(cad + j)) {
if (!isdigit(*(cad + j)))
flag = 1;
j++;
k = ++;
}
if (!flag && k == 4) {
i = atoi(cad);
q = newnode();
q->num = i;
stack(&pi,q);
}
else
printf("Wrong number");
printf("Enter a number 0 to end:");
gets(str);
}
答案 0 :(得分:0)
我想你想要这个
#include <stdio.h>
#include <stdlib.h>
int
is_valid_number(const char *const string, int *value)
{
char *endptr;
*value = strtol(string, &endptr, 10);
return (((endptr - string) == 4) && (*endptr == '\0'));
}
int
main(void)
{
int value;
const char *string = "001";
if (is_valid_number(string, &value) != 0)
fprintf(stdout, "it's valid: %d\n", value);
else
fprintf(stdout, "\033[31mINVALID\033[0m\n");
return 0;
}
答案 1 :(得分:0)
OP在正确的轨道上(除了gets()
)
char str[50];
fputs("Enter a number 0 to end:", stdout);
while (fgets(str, sizeof str, stdin) != NULL)) {
str[strcspn(str,"\n")] = '\0'; // lop off potential trailing \n
if (strcmp(str, "0") == 0) {
break;
}
#define N 4
int all_digits = 1;
for (int j = 0; j<N; j++) {
if (!isdigit((unsigned char) str[j])) {
all_digits = 0;
break;
}
}
if (all_digits && str[N] == '\0') {
i = atoi(str);
...
}
else
fputs("Wrong number", stdout);
...