I'd like to know how to limit an input value to signed decimals using std::cin
.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
cin's >> operator works by reading one character at a time until it hits whitespace. That will slurp the whole string
-1a2.0
, which is obviously not a number so the operation fails. It looks like you actually have three fields there, -1, a, and 2.0. If you separate the data by whitespace, cin will be able to read each one without problem. Just remember to read achar
for the second field.Something like:
Should read your signed "decimal" fine.
You'll need a loop and some code to make sure it handles invalid input in a sensible way.
Good luck!
I'm not trying to be rude. I just wanted to share a solution I provided which I believe is more robust and allows for better input validation.
Please refer to: My Solution to Input Validation
This also gives an error message with the input -1a2.0 avoiding the assignation of just -1 to i.
If the backing variable of the
cin
is a number, and the string provided is not a number, the return value is false, so you need a loop:Combining the techniques from the top answer here and this website, I get
input.h
Usage
inputtest.cpp
Sample run
Enter an integer: a
Invalid input.
Enter an integer: 2b
Invalid input.
Enter an integer: 3
You entered: 3.