c++ - 做.. while 循环 : How should I do so that the input (int) does not include digit '1' or '0' ?

标签 c++

do
{
    cout << "Enter a positive integer: ";
    cin >> n;

}while ( n <= 1 || n == 0);

我应该如何编码,以便如果我输入“1234”,它会拒绝,因为那里有一个数字“1”。

最佳答案

一种方法是从用户输入一个 std::string,然后使用 std::string::find 查看是否存在 0 或 1。完成后,尝试将字符串转换为整数。

或者,如果你想保留所有“数字”,你总是可以使用 % 10 来提取最右边的数字:

if (n % 10 < 2){
    /*not allowed: I'm assuming n is positive here*/
}

紧随其后

n/= 10

删除该数字,然后重复,直到剩下零。显然,您需要分别测试从 0 开始的 n 的特殊情况。

关于c++ - 做.. while 循环 : How should I do so that the input (int) does not include digit '1' or '0' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40152294/

相关文章:

c++ - 与 char 相比的位域大小

c++ - 在 Linux 和 Windows 中启用 curses

c++ - 如何在工厂中为延迟实例化指定具体类/如何延迟构造函数调用

c++ - 用 Eigen 求解小型齐次线性系统的最快方法

c++ - RTTI 与 final 一起使用吗?

c++ - 了解子集之和

c++ - 在 C++ 中并行读取大文本文件

c++ - 返回值类型中的 boost::resulf_of 或 BOOST_TYPEOF

c++ - 十进制数字的区域设置感知编辑控件子类化(格式 [sign] [xxx...] [decimal separator] [yy...] )

c++ int 数组 - 删除一个 int 并移动数组的其余部分