我有以下代码,提示用户输入仅包含数字的代码。如果用户两次输入了无效代码,则程序将继续输入无效代码。
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()
检查字符串长度)。这将更容易形成循环。
关于c++ - C++代码循环问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41218740/