gpt4 book ai didi

c - 验证 scanf

转载 作者:行者123 更新时间:2023-11-30 15:43:39 25 4
gpt4 key购买 nike

我还是 C 语言新手,正在尝试验证用户的输入。它必须采用“C”int int int 或“L”int int int 的形式。他们也可以输入任意数量的内容。我测试第一个字符,然后采用后面的 3 或 4 个整数 - 这些整数用于在其他函数中创建一些结构。我无法开始工作的是底部的其他部分。我希望它拒绝任何不是 l/L/c/C 的“类型”

到目前为止我已经

   counter = 0 ;
while ( type != '\n' )
{

scanf("%c", &type) ;
if ( type == 'L' || type == 'l')
{
scanf(" %d %d %d %d", &llx, &lly, &urx, &ury) ;
Line line = makeline(llx,lly,urx,ury) ;
shape = makeshapeline( line ) ;
box = makeboxshape( shape ) ;
counter++ ;
}
else if ( type == 'C' || type == 'c')
{
scanf(" %d %d %d", &x, &y, &rad) ;
Circle circle = makecircle(x, y, rad) ;
shape = makeshapecircle( circle ) ;
box = makeboxshape( shape ) ;
counter++ ;
}
else
{
printf("Invalid input\n") ;
return 0 ;
}

if (counter == 1)
{
boxfinal = box ; //On the first run initialise the final box to the first result
}

if (counter > 1)
{
boxfinal = makeboxbox( box, boxfinal) ;
}
}

非常感谢

最佳答案

您可以考虑使用 %s 而不是 %c 进行 scanf 扫描,然后解析结果字符串。原因是 scanf("%s", str) 会自动忽略空格,但 scanf("%c", char) 会返回空格字符,例如 \n,这是你不想要的。

编辑:作为更一般的说明,正如一些评论中已经提到的那样,如果您只提取字符串、整数,则无需担心在 scanf 系列函数中插入空格,和 float (也许我忘记了),因为这些函数在提取这些数据类型时都忽略输入字符串中的空格。 (除非用户另有指定,否则提取的字符串将始终不含空格。)

关于c - 验证 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19800017/

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