C++ - Check if a value is a number

Issue

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?

Solution

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

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

Thanks to fiddy for this tip.

Ask a question
CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jean-François Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.
This document, titled « C++ - Check if a value is a number », is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).