C 代码循环问题
C++ code loop issue
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;
}
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 在java中解决这段代码时面临循环中的问题
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 退出简单while循环时出现问题
- 循环无限运行C++解决骑士之旅问题
- Visual Studio 2017循环自动向量化问题
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 嵌套While循环不起作用(C++问题)
- 使用 GMP 的 while 循环出现问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- OpenMP for 循环并行性问题
- 这个返回元素位置的基于循环的函数有什么问题?
- 为什么循环会导致指针出现问题?
- 使用基于范围的循环迭代矢量时出现问题
- 在 c++ 中循环遍历数组时遇到问题
- 运行无限循环的最小二叉树问题
- 在C++中循环访问自定义结构列表的小问题
- 在 for 循环中更新两个变量时遇到问题C++