福尔。while 循环:我应该怎么做,使输入 (int) 不包含数字 '1' 或"0"?

Do.. while loop: How should I do so that the input (int) does not include digit '1' or '0'?

本文关键字:包含 数字 int 我应该 循环 while 输入 福尔      更新时间:2023-10-16
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

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