C++ - Check if a value is a number

October 2016


I need a routine to check if a particular is a number in order to prevent a C++ program to crash. Can you please give me an example of how it should be like?


What you can do is test the value returned by cin.

int nbJoueur=0;
cout << "nombre:";
while( !(cin >> nbJoueur) ) {
string tmp;
cin >> tmp;
cout << "incorrect" << endl;

Thanks to fiddy for this tip.

Related :

This document entitled « C++ - Check if a value is a number » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.