我有这段代码,可以确保用户输入一个N位数字(没有前导零)。我是C++的新手,但我认为这种方法是正确的。如果有任何问题,请更正。
#include <iostream>
#include <string>
#include <cmath>
std::string get_input(int n) {
std::string guess;
do
{
std::cout << "Enter a " << n << "-digit Number: ";
std::cin >> guess;
} while( (guess.length() != n) && (std::stoi(guess) / std::pow(10,n) == 0) );
return guess;
}
int main() {
int n {};
std::cout << "Enter N: ";
std::cin >> n;
std::string guess{get_input(n)};
return 0;
}
该程序接受任何长度的字符串(数字)。解决方案的哪一部分似乎有问题?PS:我使用C++ 17(
--std=c++17
)编辑:添加执行示例
最佳答案
您的逻辑不正确。当输入字符串长度不合适或输入字符串中有一些前导零时,您需要继续询问输入。
因此,您的条件应为:
do {
// ...
} while ((guess.length() != n) || (std::stoi(guess) / std::pow(10,n) == 0))
另外,除了使用
std::pow
和std::stoi
之外,您还可以像这样检查前导零:do {
// ...
} while ((guess.length() != n) || (guess[0] == '0'))
关于c++ - C++ &&运算符未评估条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63565866/