需要有cout / cin的有效输入 [英] Requiring valid input with cout/cin

查看:149
本文介绍了需要有cout / cin的有效输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个游戏,用户需要在一定范围内输入x和y坐标,一次一个。现在我的输入代码如下:

I have a game where the user needs to enter x and y coordinates within a certain range, one at a time. Right now my input code is as follows:

do {
    printf("\n");
    cout << "X: ";
    cin >> x;
    cout << "Y: ";
    cin >> y;
} while (cin.fail());

我刚接触c ++,但是阅读文档使我相信这是一个可以接受的验证用户输入。它在输入有效时工作得很好,但是当输入是不同类型(例如输入a)时,它用X:Y:无限循环。

I'm new to c++ but reading documentation lead me to believe this was an acceptable method for verifying user input. It works perfectly when the input is valid, however when the input is of a different type (for instance entering "a") it infinitely loops with "X: Y: ". What do I need to do differently to have it wait for user input as if the lines were being read for the first time?

推荐答案

考虑如果我跳过无效的输入并输入: 3e4 40。我的意思是34 40,但是跳过e可能会使3 4,并留下40用于以后或可能离开4 40。

Consider if I skip invalid input and enter: "3e4 40". I meant "34 40", but skipping the e might make "3 4" and leave "40" for later or might leave "4 40".

a href =http://en.cppreference.com/w/cpp/string/basic_string/getline =nofollow> getline 读取整行并解析它,例如使用 istringstream 就像你现在 - 任何错误变成一个错误,而不离开输入流在一个奇怪的状态。

Consider using getline to read a whole line in and parsing it such as with istringstream just as you are now -- any error becomes an error without leaving the inputstream in a weird state.

这篇关于需要有cout / cin的有效输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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