When a return type is
bool
, return
true
or
false
.
All of your inputs with "+" are invalid because they are longer than 2 digits, a condition you implemented at line 60.
Your loop at line 71 only checks the first digit, what If I type ""1a12"?
but is there another way? |
Two other simple ways.
The first method is to understand that if your program extracts an
int
, but give the program a string, then you break the cin object. Such a break can be detected and fixed:
1 2 3 4 5 6 7 8 9 10
|
int i;
cout << "Please enter a number: ";
while (!(cin >> i)) // if the extraction breaks the cin object
{
cin.clear(); // fix it
cin.ignore(80, '\n'); // clear the buffer of whatever broke it
cout << "That wasn't a number. Try again: ";
}
cin.ignore(80, '\n'); // keep the buffer clean
cout << "Your number is: " << i << endl;
| |
C offers a way to convert a c-string into a number, such math is possible to do yourself.
However, I would imagine that certain c-string functions (length, erase, etc) were written so many times by so many different people that the creators of C++ wanted the entire string class. While c++ strings can be converted to c-strings and then have c methods used on them, the C++ way is to use string streams. A string stream is just like cin/cout, but it is given strings instead, making it very easy to convert a string to any number you want (no need for the many c-string conversion functions).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
stringstream myStream;
string word;
int number;
cin >> word;
myStream << word;
myStream >> number; // if this fails, number equals zero
cout << "The word you typed was: " << word << ". The number is: " << number << endl;
return 0;
}
| |
Note that leading '+' and '-' are something the >> extractor can handle on it's own.