如何在指定C代码中添加while或jmp(汇编)处理非法输入?
实现输入验证的循环功能
我帮你把代码改成带输入验证的版本,用C标准的do-while循环就可以轻松实现需求——这样比直接用汇编jmp更易读、更符合C语言的编码习惯,毕竟汇编指令会让代码失去可移植性,而且完全没必要在这里用底层指令。
修改后的代码如下:
#include <stdio.h> #include <string.h> // 假设你已经定义了这两个函数 void TriaEqui(int l) { /* 你的函数实现 */ } void TriaIsoc(int b, int h) { /* 你的函数实现 */ } int main() { char tipo[20]; const char Equ[] = "equilatero"; const char Ret[] = "retangulo"; const char Iso[] = "isoceles"; int l, b, h; int input_valido = 0; // 标记输入是否有效 do { printf("digite o tipo de triangulo desejado:\n equilatero ou retangulo/isoceles\n"); scanf("%19s", tipo); if (strcmp(tipo, Equ) == 0) { printf("digite o valor do lado \n"); scanf("%d", &l); TriaEqui(l); input_valido = 1; // 输入有效,准备退出循环 } else if (strcmp(tipo, Ret) == 0) { printf("digite a base: "); scanf("%d", &b); printf("digite a altura: "); scanf("%d", &h); TriaIsoc(b, h); input_valido = 1; } else if (strcmp(tipo, Iso) == 0) { printf("digite a base: "); scanf("%d", &b); printf("digite a altura: "); scanf("%d", &h); TriaIsoc(b, h); input_valido = 1; } else { printf("escolha uma das 3 opcoes!\n"); input_valido = 0; // 输入无效,继续循环 } } while (!input_valido); // 只要输入无效,就重复提示 return 0; }
关键细节说明:
- 用
do-while循环确保至少执行一次输入操作,完美适配这种"先输入、后验证"的场景。 - 新增
input_valido变量跟踪输入状态:用户选对选项时设为1,循环终止;否则保持0,继续弹出提示。 - 把字符串常量改成
const,这是C语言的最佳实践,避免意外修改常量值。 - 微调了提示语的格式,比如加冒号和换行,让用户输入时更清晰。
如果你非要用类似汇编jmp的逻辑(虽然不推荐),可以用C的goto语句(本质是封装后的跳转),写法如下:
#include <stdio.h> #include <string.h> void TriaEqui(int l) { /* 你的函数实现 */ } void TriaIsoc(int b, int h) { /* 你的函数实现 */ } int main() { char tipo[20]; const char Equ[] = "equilatero"; const char Ret[] = "retangulo"; const char Iso[] = "isoceles"; int l, b, h; inicio_input: // 跳转标记 printf("digite o tipo de triangulo desejado:\n equilatero ou retangulo/isoceles\n"); scanf("%19s", tipo); if (strcmp(tipo, Equ) == 0) { printf("digite o valor do lado \n"); scanf("%d", &l); TriaEqui(l); } else if (strcmp(tipo, Ret) == 0) { printf("digite a base: "); scanf("%d", &b); printf("digite a altura: "); scanf("%d", &h); TriaIsoc(b, h); } else if (strcmp(tipo, Iso) == 0) { printf("digite a base: "); scanf("%d", &b); printf("digite a altura: "); scanf("%d", &h); TriaIsoc(b, h); } else { printf("escolha uma das 3 opcoes!\n"); goto inicio_input; // 跳转到输入起始位置,重新提示 } return 0; }
注意:goto虽然等价于汇编jmp,但在C语言里除非是处理错误或跳出多层循环,否则一般不建议使用——它会让代码的流程逻辑变得混乱,后期维护起来更麻烦。
内容的提问来源于stack exchange,提问作者guilherme cabrals
相关产品推荐
相关产品推荐

