【问题标题】:Validating lenght of digits and number验证数字和数字的长度
【发布时间】:2016-01-29 00:18:45
【问题描述】:

我一直在为一个项目而苦苦挣扎,所以我必须在 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);
}

【问题讨论】:

  • 你的代码不可读。并且不要使用 gets() 它已被弃用。你读过strcmp() 做了什么吗?
  • 这部分i need to validate 0001 but no 1. 我不清楚。你能给我们一个例子来说明它应该在哪里失败和应该在哪里成功
  • 如果你输入 1 应该是无效的 如果你输入 0001 应该是有效的这就是为什么我使用一个 char 字符串来按数字验证数字
  • 但这是一个通用的验证规则还是0001 是唯一有效的值?如果是这样,您想检查它是否有 4 个字符并且是一个数字?

标签: c validation char int type-conversion


【解决方案1】:

我想你想要这个

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

【讨论】:

  • is_valid_number(" 0",...), is_valid_number("-123",...) 会通过。
  • @chux 很好的观察,但是让我们看看 OP 是否可以从这里解决...因为一个简单的if ( ... &lt; 0) 就可以了。
【解决方案2】:

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);
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 2022-12-24
    • 2014-12-07
    • 2019-05-25
    • 1970-01-01
    相关资源
    最近更新 更多