Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

In c++ how to make only one cin number allowed?

0 votes
asked Jan 3, 2021 by Rez (120 points)
I am new to programming. I wrote the following as a practice. From what I wrote the cin/s can be any numbers. But I want to make the cin/s only accept certain numbers. Please help!

Please see the following:

#include <iostream>

using namespace std;

main(){
    
    int a;
    float c, d;
    c = 115.5;
    d = 57.75;
    a = 57;
    
    cout << "What is 65 + 50.5?"<<endl;
    cin>> c;
    cout << "Now make the result in half."<<endl;
    cin>> d;
    cout << "Great. What will remain when you take the 0.75 out?"<<endl;
    cin>> a;
   
}

1 Answer

0 votes
answered Jan 7, 2021 by Peter Minarik (86,040 points)

Well, after you read your variable via std::cin, then you have to check their values.

E.g. the following code keeps reading as long as the user doesn't enter a number between 1 and 100

#include <iostream>

int main()
{
    int number;
    do
    {   std::cout << "Please, enter a number between 1 and 100 (inclusive): ";
        std::cin >> number;
    } while (number < 1 || number > 100);
    
    std::cout << "You entered: " << number << std::endl;
    
    return 0;
}

Does this help?

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...