gpt4 book ai didi

c - 如何在 C 中使用 try-catch(或 C 中的等效项)

转载 作者:行者123 更新时间:2023-11-30 20:13:53 24 4
gpt4 key购买 nike

我需要弄清楚如何使用 try catch 等效于检查用户是否输入了太多字符,是否输入了“+、-、*、/或%”之外的符号,或者用户是否输入了除 1 之外的其他内容或 0(位 1 或位 2)。

    printf("This program will do the equation (+, -, *, /, %) which a user will input, a 7bit binary number, a sign, and then another 7bit binary number and print the answer.\n\n");

printf("Please enter the equation.\n");
scanf("%7s%c%7s", bits1, &sign, bits2);

最佳答案

C 中没有 try-catch,只需使用 if 语句即可。

scanf之后,检查

if(sign!='+' && sign!='-' && sign!='/' && sign!='*' && sign!='%') //if sign is an invalid character
handle_bad_input();
else
{
int i,len=strlen(bits1);

for(i=0;i<len;i++) //for looping through each character
if(bits1[i]!='0' && bits1[i]!='1') //if the character is not 0 or 1
handle_bad_input();

len=strlen(bits2);
for(i=0;i<len;i++)
if(bits2[i]!='0' && bits2[i]!='1')
handle_bad_input();
}

请注意,为了使其按预期工作,应初始化 bits1bits2scanf 可能会失败。所以,如@MattMcNabb在评论中指出,检查 scanf 的返回值是一个好主意。 scanf 返回成功填充的参数列表的项目数。该计数可以与预期的项目数匹配,也可以由于匹配失败、读取错误或到达文件结尾而减少(甚至为零)。并且,如果其中任何一个发生在任何数据之前可以成功读取,返回EOF。在你的例子中,成功时它将返回 3。

关于c - 如何在 C 中使用 try-catch(或 C 中的等效项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28597603/

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