限制用户只能在C ++中输入实数 [英] Restrict user to input real number only in C++

查看:128
本文介绍了限制用户只能在C ++中输入实数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制用户只能在C ++程序中输入实数?

How can I restrict the user to input real numbers only in C++ program?

示例:

double number;
cin >> number;

double number; cin >> number;

它不会接受输入:'12add','abcd'etc ...

and it won't accept the input like: '12add' , 'abcd' etc...

有人可以指导我吗?使用bool值。
谢谢!

can someone guides me to that? using bool value. Thanks!

推荐答案

您不能强制用户给出正确的输入。但是,如果上一个无效,您可以要求他们提供另一个输入。有不同的程序这样做。一个是以下内容:

You cannot force the user to give correct input. But you can ask them to give another input if previous was invalid. There are different procedures to do so. One is the following:


  1. 使用
  2. 解析并理解该行
  3. >
  4. 如果行无效,请向用户提供错误,然后转到1

  1. Use getline to read a line
  2. Parse and understand the line
  3. If line is invalid, give error to user and go to 1

。它使用动态内存。另一个选项是:

This is alright and quite common. It uses dynamic memory though. Another option would be:


  1. 使用 cin>> c> $ c> c> (检查 cin.eof()也)

  2. 如果失败,请忽略所有输入,直到空白:

  1. Use cin >> value; like you normally do
  2. Check cin.fail() to see if input was correctly read (check for cin.eof() also)
  3. If failed, ignore all input until whitespace:

char c;
while (cin >> c)
    if (isspace(c))
        break;


输入如下:

abc 12.14

您不会忽略整行,而只是 abc

you don't ignore the whole line, but just the abc.

这篇关于限制用户只能在C ++中输入实数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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