当用户在scanf()中输入错误的数据类型时,如何解决无限循环? [英] How to fix infinite loops when user enters wrong data type in scanf()?

查看:344
本文介绍了当用户在scanf()中输入错误的数据类型时,如何解决无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C初学者在这里.对于下面的程序,每当用户输入字符或字符串时,就会进入无限循环.在仍使用scanf的同时如何解决此问题?与使用scanf相比,编写此程序的更好方法是什么?感谢那些会回答的人.

C beginner here. For the program below, whenever the user inputs a character or a string it enters an infinite loop. How would you fix this while still using scanf? And what would be the better methods of writing this program rather than using scanf? Thanks to those who will answer.

#include <stdio.h>
#include <ctype.h>

int main() {

int rounds = 5;

do {
printf("Preferred number of rounds per game. ENTER NUMBERS ONLY: ");
scanf("%d", &rounds);   
} while(isdigit(rounds) == 0);

return 0;   
}

推荐答案

我会说只有两个修复程序".

I'd say there are just two "fixes".

  1. 保留scanf呼叫,疣和所有呼叫.当scanf需要数字时,请小心不要输入非数字.

  1. Retain the scanf call(s), warts and all. Carefully refrain from typing non-digits when scanf is expecting digits.

放弃scanf并使用其他东西.我们刚刚在上讨论了这种策略问题.

Abandon scanf and use something else. We've just been discussing this tactic over at this new question.

一旦您使用scanf,总是很想尝试修复"它,因此这里可能潜藏着第三个答案,解释了如何在仍旧的情况下做得更好,更人性化,更具容错性的输入使用scanf.但是,我认为这是一个傻瓜的事,是在浪费时间.对scanf的许多缺陷的简单,明显的修复方法本身并不完善,并且还有其他缺陷.与不使用scanf重写该程序相比,您可能花费更多的时间来尝试修复使用scanf的程序,并且使用非程序将获得总体上更好的结果(更不用说更干净的程序了). -scanf-仍然使用重写.

Once you're using scanf, it's always tempting to try to "fix" it, so there's potentially a third answer lurking here, explaining how to do better, more user-friendly, more error-tolerant input while still using scanf. In my opinion, however, this is a fool's errand, a waste of time. The easy, obvious fixes for scanf's many deficiencies are themselves imperfect and have further deficiencies. You will probably spend more time trying to fix a scanf-using program than you would have spent rewriting it to not use scanf -- and you'll get overall better results (not to mention a cleaner program) with the non-scanf-using rewrite anyway.

这篇关于当用户在scanf()中输入错误的数据类型时,如何解决无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆