【问题标题】:C++: Just allow numbers as an input [duplicate]C ++:只允许数字作为输入[重复]
【发布时间】:2021-01-15 04:24:45
【问题描述】:

我想在下面的代码中阻止所有字母输入,你能帮我吗?

#include <iostream>
using namespace std;

int main()
{
cout<<"To close this program you need to type in -1 for the first input"<<endl;
int m, n;
do{

 int counter1 = 0;
 int counter2 = 0;
 cout<<"Now you need to input two seperate natural numbers, and after that it calculates the difference of both numbers factors!"<<endl;

 cout<<"First Input"<<endl;
 cin>>m;
 if(m==-1){
    break;
 }
 cout<<"Second Input"<<endl;
 cin>>n;
if(m<0 or n<0){
    cout<<"ERROR - Only natural numbers are allowed!"<<endl;
}
else{
...

程序的其余部分只是数学运算。

【问题讨论】:

  • 请发帖minimal reproducible examplemn 声明在哪里?
  • m 和 n 是整数
  • 不能屏蔽输入但可以检测到无效输入。
  • 只要mn 的类型为int,尝试输入字母将失败,并将值0 分配给变量。
  • 对于您未向我们展示的代码,我们无法为您提供帮助。请包括minimal reproducible example。细节很重要

标签: c++ integer iostream cin


【解决方案1】:

当您声明变量的类型时,该变量不能包含您声明的内容以外的任何内容。所以:你不能使用int m 来输入浮点数。但是,您可以使用cin.ignore() (more details here) 接受用户输入的“4.1”作为“4”。给你:

#include <iostream>
#include <limits>

using namespace std;

int main() {
    cout << "Enter an int: ";

    int m = 0;
    while(!(cin >> m)) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input!\nEnter an int: ";
    }

    cout << "You enterd: " << m << endl;        
}

【讨论】:

    猜你喜欢
    • 2018-08-05
    • 2017-08-11
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 2021-11-18
    • 1970-01-01
    相关资源
    最近更新 更多