I'm obviously a noob @ c++.
Have a question.
is there any way i can restrict user to input only numeric value and make a loop if user enters non-numeric value.

for example for conversion from kilo to pound if user enters some garbage like "afshdgafg" in cin. is there any way i can make user pay for it and make it a loop?

Thanks in advance.

5 Years
Discussion Span
Last Post by parth27987

You can not charge a user money. You can, however, ensure that what they input matches what you require. Read this thread for a decent set of examples.


You could put an if statement after the the user inputs data and if there input does equal what you want then allow them to keep entering until it does.


well the program converts temperature from one unit to another. how can i restrict them to just enter numerical values and not any characters? i know the buffer system in c++ just sucks but there should be some way don't u think so?


It is quite easy to check the validity with C++'s formatted input mechanism, which will fail if the input is not of the required format.

Personally, I don't like to fiddle around with the std::cin too much, so I would recommend the intermediate use of std::stringstream.

Something like this would do:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {

  int value = 0;
  while(true) {
    cout << "Please enter an integer number: ";
    string tmp;
    getline(cin, tmp);
    if( stringstream(tmp) >> value )
  return 0;
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.