Hi,
I have a program which needs to accept a date,
it can only accept under 30 days, and the entry has to be over 0

My problem is that it accepts anything, it doesnt make sense because i have used the exact layout on other bits of code which work perfectly,

do {  
     cout << "Please enter day: ";
     cin >> day;
     system("cls");
     }
     while ((day >= 0) & (day <= 30));
     cout << "Day Accepted";
     Sleep(1000);
     system("cls");

All it does is go straight to day accepted no matter what,
i have tried using { on the while part,
i am using devcpp

Dani AI

Generated

The do/while was doing the opposite of what you wanted: a do/while repeats while its condition is true, so the condition should describe the invalid input you want to keep asking for, not the valid input you want to accept. For "greater than 0 and less than 30" that means keep looping while day <= 0 || day >= 30. Also validate stream input so non-numeric entries don't leave cin in a failed state.

Example (robust, not using system or Sleep):

#include <iostream>
#include <limits>

int main() {
    int day = 0;
    do {
        std::cout << "Enter day (1..29): ";
        if (!(std::cin >> day)) {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Not a number. Try again.\n";
            continue;
        }
    } while (day <= 0 || day >= 30);

    std::cout << "Day accepted: " << day << '\n';
}

Use &&/|| for boolean logic (preferred) rather than relying on the single & between relational expressions; & can compile but is a bitwise operation and does not short‑circuit. See the C++ logical operators reference for details: logical operators. For safe input handling consult the stream extraction docs: operator>>.

Tying back to the thread: was pointing toward operator choice and noted that a single ampersand compiles but behaves differently; , switching to a condition that uses || to test the invalid range is the right fix. When debugging, avoid clearing the screen immediately so you can see error messages or the raw input value.

Recommended Answers

All 4 Replies

you know that in c++ you cant use " & " alone for the "and" purpose right?

try " && " thats the "and" or try " || "

you know that in c++ you cant use " & " alone for the "and" purpose right?

You can (with proper care), but it's not short circuited and tends to be confusing. I don't know anyone who would let & instead of && slide during a code review.

sorry my bad :) i learn by my self and didn't knew that & could be used for "and" too.

Hi, Solved the problem with ||

I did usually use && and had tried with no avail using that,
It was confusing because some of my other loops work with just &

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.