schegu
schegu

Reputation: 31

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). I am new to C++ but I feel the approach is correct. 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)

Edit: Add execution example

exec

Upvotes: 1

Views: 158

Answers (2)

R Sahu
R Sahu

Reputation: 206707

&& 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) );

Upvotes: 4

cigien
cigien

Reputation: 60268

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:

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

Upvotes: 2

Related Questions