gpt4 book ai didi

c - 使用 scanf() 进行验证以防止字符串

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:55 26 4
gpt4 key购买 nike

我这里有一段代码,用于查看用户输入是字符串还是 1-49 范围内的整数。如果我输入“asdas”它说无效,如果我输入一个“1-49”的整数它说有效。我在使用这段代码时遇到的问题是,如果我输入“2 asda”它会同时计算有效和无效,如果我输入“2 2”,它也会认为有效。刚刚发现它也接受“2d”作为有效输入。

for (i = 0; i < 6; i++)
{

printf("\nPlease enter the %d winning ticket numbers!: ", i+1);
if (scanf("%d", (&winningNumbers[i])) == 0 || (winningNumbers[i] <= 0) || (winningNumbers[i] >= 50))
{
inputFlush();
printf("\nInvalid Input. Please re-enter.\n") ;
i = i - 1;
}
}

for (i = 0; i < 6; i++)
{
printf("%d, ", winningNumbers[i]);
}

最佳答案

将整行读入一个字符串(fgets,片段中的第 2 行)。使用 sscanf 从字符串中读取数据:读取整数一个空格之后。检查 sscanf 是否返回与 1 不同的值。如果是,那么您要么在开头有字符串(它返回 0,因为它无法读取整数),要么在末尾有额外的空白字符 (也就是说它也匹配 %c 格式说明符)。需要空格来跳过空格直到行尾(包括存储的\n)。

printf("\nPlease enter the %d winning ticket numbers!: ", i+1);
fgets(buffer, size, stdin);
if (sscanf(buffer, "%d %c", &winningNumbers[i], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
// inputFlush(); not needed now that you read the entire line
printf("\nInvalid Input. Please re-enter.\n") ;
i = i - 1;
}

关于c - 使用 scanf() 进行验证以防止字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20039429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com