c - 如何在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);
}
解决方案
您可以使用在条件中定位数组strcspn
的末尾,您可以返回数组的大小直到它找到(或者因为您似乎没有从数组中删除它),然后您可以使用它来设置输入的最小尺寸。char
while
char
'\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
因为您将大小限制fgets
为17
,因此它将存储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);
}
推荐阅读
- java - Annotation of multiple types of annotation
- android - disable app usage tracking temporily
- c# - 听写不适用于我的 WPF 应用程序 - 需要建议
- rest - 如何在招摇中更改查询参数名称?
- c - 为什么 fgets 会读取我在 scanf 中的第一个输入?
- javascript - 使用 Javascript 选择嵌套元素
- javascript - 如何仅在第一页加载时显示弹出窗口
- c++ - 想要检测特征并在 2 个不同的帧中匹配特征
- sas - 如何在SAS中按字母顺序对地址进行排序?
- javascript - ReactJS API 数据获取 CORS 错误