检查用户输入到一个数组太长? [英] Check if user input into an array is too long?

查看:93
本文介绍了检查用户输入到一个数组太长?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到用户输入4个数字。他们可以输入:1 2 3 4或1234或1 2 34,我目前使用等。

I am getting the user to input 4 numbers. They can be input: 1 2 3 4 or 1234 or 1 2 34 , etc. I am currently using

int array[4];
scanf("%1x%1x%1x%1x", &array[0], &array[1], &array[2], &array[3]);

不过,我想显示一个错误,如果用户输入了太多的数字:12345或1 2 3 4 5或1 2 345等

However, I want to display an error if the user inputs too many numbers: 12345 or 1 2 3 4 5 or 1 2 345 , etc.

我怎样才能做到这一点?

How can I do this?

我很新的C,所以请解释尽可能多的。

I am very new to C, so please explain as much as possible.

//

感谢您的帮助。
现在什么我试图做的是:

Thanks for your help. What I have now tried to do is:

char line[101];
    printf("Please input);
    fgets(line, 101, stdin);
    if (strlen(line)>5)
    {
        printf("Input is too large");
    }
    else
    {
        array[0]=line[0]-'0'; array[1]=line[1]-'0'; array[2]=line[2]-'0'; array[3]=line[3]-'0';
        printf("%d%d%d%d", array[0], array[1], array[2], array[3]);
    }

这是一个明智的和可接受的方式是什么?它编译,并显示在视觉工作室工作。它会编译和运行C?

Is this a sensible and acceptable way? It compiles and appears to work on Visual Studios. Will it compile and run on C?

推荐答案

OP是在正确的轨道上,但需要调节处理错误。

OP is on the right track, but needs adjust to deal with errors.

目前的方法,使用 scanf()的可用于的检测的问题,但没有得到很好的恢复。相反,使用与fgets()/的sscanf()组合。

The current approach, using scanf() can be used to detect problems, but not well recover. Instead, use a fgets()/sscanf() combination.

char line[101];
if (fgets(line, sizeof line, stdin) == NULL) HandleEOForIOError();
unsigned arr[4];
int ch;
int cnt = sscanf(line, "%1x%1x%1x%1x %c", &arr[0], &arr[1], &arr[2],&arr[3],&ch);
if (cnt == 4) JustRight();
if (cnt < 4) Handle_TooFew();
if (cnt > 4) Handle_TooMany();  // cnt == 5 

CH 捕捉任何潜伏非空白字符 4号之后。结果
使用%1U 如果找1十进制数到无符号。结果
使用%1D 如果找1十进制数到 INT

ch catches any lurking non-whitespace char after the 4 numbers.
Use %1u if looking for 1 decimal digit into an unsigned.
Use %1d if looking for 1 decimal digit into an int.

OP第二方法数组[0] =行[0] - '0'; ... ,是不坏,但有一些缺点。它不执行良好的错误检查(非数字),也不是处理十六进制数字像第一。此外,它不允许领先或穿插空格。

OP 2nd approach array[0]=line[0]-'0'; ..., is not bad, but has some shortcomings. It does not perform good error checking (non-numeric) nor handles hexadecimal numbers like the first. Further, it does not allow for leading or interspersed spaces.

这篇关于检查用户输入到一个数组太长?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆