Tricky Tricks ›› Programming Tricks ›› C Languages Tricks ›› Reading In Numbers Directly Is Problematic

Reading In Numbers Directly Is Problematic

C Programming Tricks

Reading in numbers directly is problematic:

 If std::cin is presented with input it cannot process, std::cin goes 
 into a "fail" state
 
 The input it cannot process is left on the input stream.
 
 All input will be ignored by std::cin until the "fail" state is 
 cleared: std::cin.clear()
 
 A routine that reads a number directly should: 
 Read in the number
 Check to see that the input stream is still valid
 If the input stream is not good (!std::cin)
 Call std::cin.clear() to take the stream out of the "fail" state.
 Remove from the stream the input that caused the problem: 
 std::cin.ignore(...)
 
 Get the input again if appropriate or otherwise handle the error
 Inputing numbers directly, version 1: 
 
 
   #include //for nuumeric_limits
   float fl;
   int bad_input;
   do{
     bad_input=0;
     std::cin >> fl;
     if(!std::cin)
     {
       bad_input=1;
       std::cin.clear();
       std::cin.ignore(std::cin.ignore(std::numeric_limits::max(),'\n');
     }
 
   }while(bad_input);
 Inputing numbers directly, version 2: 
 
   #include //for nuumeric_limits
   float fl;
   while(!(std::cin >> fl))
   {
     std::cin.clear();
     std::cin.ignore(std::cin.ignore(std::numeric_limits::max(),'\n');
   }
 

A note on limits. If your compiler doesn't support std::numeric_limits::max(), an alternative is to use the c-style method for determining the maximum integer allowed:

 #include
 ...
 std::cin.ignore(INT_MAX, '\n');
 

Sitemap : Partners