Tricky Tricks ›› Programming Tricks ›› C Languages Tricks ›› Using Getline To Input Numbers

Using Getline To Input Numbers

C Programming Tricks

Using getline to input numbers is a more robust alternate to reading numbers directly:

 #include 
 ...
 int i;
 float fl;
 char temp[100];
 
 std::cin.getline(temp, 100);
 fl=strtof(temp,0);
 std::cin.getline(temp, 100);
 i=strtol(temp,0,10);
 
 

getline will read both strings and numbers without going into a "fail" state.

Include cstdlib to use the converter functions: string-to-long-integer (strtol), string-to-double (strtod), string-to-float (strtof), and string-to-long-double (strtold). Refer to a reference for more information on the second (and third for strtol) arguments to these converter functions.

Partners