Expressions régulières (c.-à-d.libpcre) à la rescousse:
// checked_atof.cpp
#include <iostream>
#include <cstdlib>
#include <pcrecpp.h>
const char FP_RE[] = "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?";
using namespace std;
int main()
{
std:string s;
double number;
pcrecpp::RE fpre(FP_RE);
cout << "Enter a floating point number: " << endl;
cin >> s;
if (!fpre.FullMatch(s)) {
cout << "Sorry, not a valid floating point number!" << endl;
} else {
number = atof(s.c_str());
cout << "Ok, result: " << number << endl;
}
return 0;
}
Pour plus de détails concernant l'installation/compilation, s'il vous plaît se référer à la documentation libpcre
- les éléments suivants peuvent fonctionner sur votre système:
g++ checked_atof.cpp $(pkg-config --cflags libpcrecpp) $(pkg-config --libs libpcrecpp) -o checked_atof
$ ./checked_atof.exe
Enter a floating point number:
23.42
Ok, result: 23.42
$ ./checked_atof.exe
Enter a floating point number:
3.14159e-4
Ok, result: 0.000314159
$ ./checked_atof.exe
Enter a floating point number:
x9
Sorry, not a valid floating point number!
Nice. Cependant, 'd' n'est pas imprimé comme non initialisé sur' invalid_argument'? – chi
@chi oui, c'était faux, je l'ai réparé avec un meilleur exemple – marcinj