【发布时间】:2020-06-22 02:02:20
【问题描述】:
我正在尝试编写一个程序来询问用户要使用的操作,它会询问两个数字。但是如果用户输入了一个数字并且上面有一个字母,程序应该重新提示用户要求另一个输入。
#include<iostream>
using namespace std;
void operation(int a);
class Numbers{
public:
int num1, num2;
float result;
};
int main(){
Numbers input;
int *ptr1 = &input.num1;
int *ptr2 = &input.num2;
float *ptr3 = &input.result;
int range = 0;
cout<<"Enter First Number: ";
while(!(cin>>*(ptr1+range))){
cout<<"That's not a number!\n";
cout<<"\nEnter First Number: ";
cin.clear();
cin.ignore(32767, '\n');
}
cout<<"Enter Second Number: ";
while(!(cin>>*(ptr1+range))){
cout<<"That's not a number!\n";
cout<<"\nEnter Second Number: ";
cin.clear();
cin.ignore(32767, '\n');
}
}
所以在这个程序中,当用户输入一个字符时,它会提示用户输入另一个字符。 但是问题是当我在一个数字中输入一个字母时,程序没有重新提示而是 它跳到下一行。
输入第一个数字:t 这不是一个数字!
Enter First Number: 4e // as you can see, this is what happens, it did not reprompt but it jumped to the next line of code
Enter Second Number: That's not a number!
Enter Second Number:
【问题讨论】:
-
你试过
e4e和44 34吗? -
@Melon 是的,它工作正常,但是当数字出现时它不会。
-
太棒了。现在正如其他人指出的那样,请使用
std::stoi请在此处查看它如何与示例一起使用,以便您更深入地了解发生了什么:en.cppreference.com/w/cpp/string/basic_string/stol
标签: c++