简体   繁体   English

C++ && 运算符不评估条件

[英]C++ && operator not evaluating the conditions

I have this piece of code which ensures that the user inputs a N-digit Number(With no leading zeroes).我有这段代码可以确保用户输入一个 N 位数字(没有前导零)。 I am new to C++ but I feel the approach is correct.我是 C++ 的新手,但我觉得这种方法是正确的。 Please correct if anything is amiss.如有不对之处请指正。

#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; 
}

This program is accepting any length string(number).该程序接受任何长度的字符串(数字)。 Which part of the solution seems wrong?解决方案的哪一部分似乎是错误的? PS: I use C++17( --std=c++17 ) PS:我使用 C++17( --std=c++17 )

Edit: Add execution example编辑:添加执行示例

执行

&& is not the correct logical operand. &&不是正确的逻辑操作数。 You need to use ||您需要使用|| . .

do
{
    std::cout << "Enter a " << n << "-digit Number: ";
    std::cin >> guess;
} while( (guess.length() != n) || (std::stoi(guess) / std::pow(10,n) == 0) );
//                             ^^

It might be easier to write and understand the code if you re-phrase the logic as:如果您将逻辑重新表述为:

bool isValidInput(string const& guess)
{
   return (guess.length() == n && (std::stoi(guess) / std::pow(10,n) != 0));
}

do
{
    std::cout << "Enter a " << n << "-digit Number: ";
    std::cin >> guess;
} while( !isValidInput(guess) );

Your logic is incorrect.你的逻辑不对。 You need to keep asking for input when the input string is either not the appropriate length OR there are some leading zeros in the input string.当输入字符串的长度不合适输入字符串中有一些前导零时,您需要继续要求输入。

So your condition should be:所以你的条件应该是:

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

Also, instead of using std::pow and std::stoi , you can check for leading zeros like this:此外,您可以像这样检查前导零,而不是使用std::powstd::stoi

do {
 // ...
} while ((guess.length() != n) || (guess[0] == '0'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM