c++ - check if user input a float to a int var? -
I have an integer; And using cin, but how do user input a float check or give me the solution to this problem? > There is no easy way to do this & gt; & Gt; Operator
is not really intended for interacting with humans, who can enter the wrong thing, you will have to read the input as a string and then use it as a string-like function, or a code rolled by your hand Have to check.
Here's the outline of an approach using Streetsol:
#include & lt; Iostream & gt; #include & lt; String & gt; # Include & lt; Cstdlib & gt; using namespace std; Bool GetInt (istream & amp; int) {string line; If (Getline (is, line)) {return false; } Four * AP; N = Strict (line c_st (), and amp; app, 10); Return * AP == 0; } Int main () {int n; While (1) {cout & lt; & Lt; "Enter an int:"; If (GetInt (cin, n)) {cout & lt; & Lt; "Integer" & lt; & Lt; Endl; } And {cout & lt; & Lt; "Not an integer" & lt; & Lt; Endl; }}}
Comments
Post a Comment