首页 > 解决方案 > 如何在c中存储具有最小和最大大小的值

问题描述

我正在尝试创建一个程序,该程序要求输入13-16数字信用卡号,并在用户输入非数值时重新提示。到目前为止,当我输入16数字值时,我的程序可以工作;但是,如果我输入更少的内容,它会重新提示。

如何让我的程序接受最少13位数和最多16位数?

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>

int main(void)
{
    long cn;
    char buf[18], *endptr;

    do
    {
        printf("card number please: ");
        fgets(buf, 17, stdin);
        cn = strtol(buf, &endptr, 0);
    } while (*endptr != '\0' || endptr == buf);

    printf("%ld\n", cn);
}

标签: ccs50strtol

解决方案


您可以使用在条件中定位数组strcspn的末尾,您可以返回数组的大小直到它找到(或者因为您似乎没有从数组中删除它),然后您可以使用它来设置输入的最小尺寸。charwhilechar'\0''\n'

#include <string.h>
//...
do{
//...
while (strcspn(buf, "") < 14); //less than 13 chars will repeat the cycle
//...

您还可以删除'\n'from buf,在这种情况下您可以使用strlen

//...
do{
    fgets(buf, 17, stdin);
    buf[strcspn(buf, "\n")] = '\0';
while (strlen(buf) < 13); //by removing '\n' you can use strlen
//... 

的最大大小buf将是16因为您将大小限制fgets17,因此它将存储16字符加上空终止符,您可以将数组的大小减小到17,因为该18th元素是无用的。

另请注意,long并不总是 8 个字节,https://en.wikibooks.org/wiki/C_Programming/limits.h

话虽这么说,代码存在继承问题,它会消耗所有内容,包括字母字符、空格等,因此如果您输入1234 1234 1234 1234, only1234将被转换为strtol.

在下面的示例中,我将删除所有不是数字的内容并维护所有其他规范:

运行示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main()
{
    long long cn; //long long is never smaller than 8 bytes
    int i, c;
    char buf[17];

    do {
        i = 0;
        printf("card number please: ");
        while ((c = fgetc(stdin)) != '\n' && c != EOF && strlen(buf) < 17) //max size 16
        {
            if (isdigit(c)) //only digits
                buf[i++] = c;
        }
        buf[i] = '\0';
    } while (strlen(buf) < 13); //min size 13

    cn = strtoll(buf, NULL, 10); //strtoll for long long

    printf("%lld\n", cn);
}

推荐阅读