Unfortunately there is no portable way to restrict the number of characters input in C++. But whatever platform you are using will provide some mechanism: for example on Windows, look up Console functions.
If you do go with plain old C++ iostreams input from cin
, it's a good idea to read the initial text into a std::string
using istream& getline(istream&, string&)
-- this will prevent buffer overflows, because string
s resize as necessary. (Your code involving getline(InputMain, 5, '\n')
is technically safe in that it won't read more than 5 characters into InputMain
, but this code is fragile -- if you later decide you want 6 characters, you could easily forget to update your call to malloc()
, leading to crashes. Also, you need to remember to free(InputMain)
. But as I said, use string
instead.)
Regarding parsing:
Whether you read the input into a string
using getline(cin, str)
or some platform-specific code, once it's in there you need to get it out in the form of a number. This is where the istringstream
class is useful -- it lets you treat an existing string
as a stream to read from, so you can use the formatted input >>
operator:
string str;
if (!getline(cin, str)) {
cerr << "Something went seriously wrong...\n";
}
istringstream iss(str);
int i;
iss >> i; // Extract an integer value from the stream that wraps str
if (!iss) {
// Extraction failed (or a more serious problem like EOF reached)
cerr << "Enter a number dammit!\n";
} else if (i < 1000 || i > 9999) {
cerr << "Out of range!\n";
} else {
// Process i
}
If you're using C++ iostreams, you can actually just extract directly from cin
instead of going via a string
and an istringstream
:
int i;
cin >> i; // Extract an integer value from cin
However this can have subtle undesirable effects; notably, any additional characters on the line typed by the user (in particular the '\n'
typed when they press Enter) will remain in the input buffer to be read by the next <<
operation. Often this doesn't matter, but sometimes it does: e.g. if you follow up with cin.get();
, expecting that this will wait for a keypress, it won't -- it will just read the '\n'
(or the first non-digit character the user typed).