强制用户以特定格式写入输入

时间:2013-10-28 18:20:34

标签: c input string-formatting scanf

我正在C中制作一个程序来跟踪仓库中的物品。

我希望强制用户至少包含一个号码! 例如dvd1,dvd2。 hello1,hello20

有没有办法做到这一点? 此刻我正在使用scanf。

我希望产品代码的xx-xxx-xxx要求格式是x是数字。

我正在使用scanf(%[0-9-] s

Mvh Anton!

2 个答案:

答案 0 :(得分:1)

scanf不能那样工作,它没有深入的验证。

您需要将输入读入char数组,然后遍历每个字符并查看它是否为数字。

像这样(未经测试):

char buffer[1000];
int i = 0, hasDigit = 0;

scanf("%s", buffer);
while (i < sizeof(buffer) && buffer[i] != 0 && !hasDigit)
{
  hasDigit = isdigit(buffer[i]);
  i++;
}

// if hasDigit is 0, there are no digits

注意:scanf不是很好,因为如果输入的字符多于缓冲区中的字符,则会导致缓冲区溢出。最好使用fgets(buffer,sizeof(buffer),stdin);

答案 1 :(得分:0)

阅读输入,您可以像This SO question中那样进行迭代。您可以检查chars是否与您想要的输入相匹配。

相关问题