C 代码循环问题

C++ code loop issue

本文关键字:问题 循环 代码      更新时间:2023-10-16

i具有以下代码,该代码提示用户输入仅包含数字的代码。如果用户两次输入无效的代码,则该程序在没有有效代码的情况下进行。

int main()
{
    char code[10];
    cout << "Enter the code: ";
    cin >> code;
    int codeLength = strlen(code);
    int i = 0;
    while (code[i] >= '0' && code[i] <= '9')
        i++;
    if (i != codeLength)
    {
        cout << "The code is not valid: " << codDat << endl;
        cout << "Enter the code again: ";
        cin >> code;
    }
    cout << code <<endl;
    return 0;
}

如何提示用户输入新代码,直到输入代码仅包含数字?我已经尝试过:

do {
    cout << "Enter the code again: ";
   cin >> code;
} while (code[i] >= '0' && code[i] <= '9');

此代码仅检查第一个字符,但我不知道如何制作正确的循环。

我倾向于阅读 std::string

std::string foo;
cin >> foo;

然后使用

bool is_only_digits = std::all_of(foo.begin(), foo.end(), ::isdigit);

检查输入是否仅包含数字。(您也可以使用foo.size()检查字符串长度)。

这将是更容易进入循环。

尝试通过以下修改代码。

while(true)
{
    i=0;
    while(i<codeLength && code[i] >= '0' && code[i] <= '9')
        i++;
    if(i != codeLength)
    {
        cout << "The code is not valid: " << codDat << endl;
        cout << "Enter the code again: ";
        cin >> code;
    }
    else
        break;
}