c++ - 整数输入仅限于四位数字

标签 c++ input

我正在做一个问题,它要求输入一个只有四位数字的帐号。这必须通过基本的初学者 C++ 来完成。

我需要找出一种方法将整数的输入限制为四位。用户应该能够输入 0043 或 9023 或 0001,它应该是一个可接受的值....

我想我知道如何用一个字符串完成它.... getline(cin,input) 然后检查 input.length()==4 吗?

但我什至不知道如何使用整数输入来做到这一点。

最佳答案

请注意,如果 0043旨在区别于 43 ,那么输入实际上不是一个数字,而是一个数字串,就像电话“号码”一样。

将该行作为字符串读取 input .

检查 input 的长度是4 .

检查字符串中的每个字符是否为<= '9'>= '0' .

类似于:

std::string read4DigitStringFromConsole()
{
    bool ok = false;
    std::string result;
    while (!ok)
    {
        std::cin >> result;
        if (result.length() == 4)
        {
            bool allDigits = true;
            for(unsigned index = 0; index < 4; ++index)
            {
                allDigits = allDigits && ( 
                    (result[index] >= '0') && 
                    (result[index] <='9') 
                    );
            }
            ok = allDigits;
        }
    }
    return result;
}

关于c++ - 整数输入仅限于四位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14514412/

相关文章:

c++ - 防止在 Windows 中取消停靠计算机

c++ - boost spirit , boost 任何和引用的字符串 - 编译时错误

c++ - 显示列表无法正常工作

ios - 触摸并拖动输入字段时无法阻止拖动页面jquery mobile phonegap ios

c++ - 将指向成员函数的指针作为指向函数的指针传递

c++ - 如何在 C++ 上将具有一定大小的数组填充到另一个具有更大大小的数组中?

list - 将数字输入到空列表 Python

c++ - 在 C++ 中将某种结构化的文本文件读入数组

c++ - 如何在用户输入 ^X 之前读取输入

android editText最大限制