c++ - C++ &&运算符未评估条件

标签 c++

我有这段代码,可以确保用户输入一个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)
编辑:添加执行示例
exec

最佳答案

您的逻辑不正确。当输入字符串长度不合适或输入字符串中有一些前导零时,您需要继续询问输入。
因此,您的条件应为:

do {
 // ...
} while ((guess.length() != n) || (std::stoi(guess) / std::pow(10,n) == 0))

另外,除了使用std::powstd::stoi之外,您还可以像这样检查前导零:
do {
 // ...
} while ((guess.length() != n) || (guess[0] == '0'))

关于c++ - C++ &&运算符未评估条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63565866/

相关文章:

c++ - 代码块 C++ 错误

c++ - 在 C++ 中,我可以使用多线程工具将 UNIX 信号与我的主程序同步吗?

c++ - 如何改进逻辑以检查 4 个 bool 值是否匹配某些情况

C++ 将派生结构传递给需要超结构的方法

c++ - MSVC : unrecognizable template declaration/definition (compiles with Clang/GCC)

C++: vector 容器和 <algorithm> std::find

c++ - 将参数从其他进程传递给守护进程

c++ - 如何编写一个 C++ 函数,根据处理返回不同类型的 std::list?

C++ 笛卡尔积迭代器在第一次迭代时调用基类函数

c++ - 对类方法进行指针部分特化时获取 "illegal use of explicit template arguments"