I’ll need to accept a string of 5 numbers from the user (only 5). Should I use
istringstream
for the same ?
Can’t I get away with something like this ?
int main() { char *InputMain; InputMain=(char *)malloc(5+1); cout << 'Enter the number : ' <<endl; cin.getline ( InputMain, 5, '\n' ); // Input goes into InputMain cout << 'The number entered is : ' << InputMain <<endl; cin.get(); }
Then comes the next part..
How’d I make sure the user inputs only 5 chars? And maybe if the user enters more than 5 chars, I should display a warning saying only 5 chars allowed..
One more question, since this essentially is a string, I’ll need to validate the input to be only numbers by parsing through each char in the string and checking against respective ASCII values (for numerals).. Is that approach the right thing?
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 astd::stringusingistream& getline(istream&, string&)— this will prevent buffer overflows, becausestrings resize as necessary. (Your code involvinggetline(InputMain, 5, '\n')is technically safe in that it won’t read more than 5 characters intoInputMain, but this code is fragile — if you later decide you want 6 characters, you could easily forget to update your call tomalloc(), leading to crashes. Also, you need to remember tofree(InputMain). But as I said, usestringinstead.)Regarding parsing:
Whether you read the input into a
stringusinggetline(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 theistringstreamclass is useful — it lets you treat an existingstringas a stream to read from, so you can use the formatted input>>operator:If you’re using C++ iostreams, you can actually just extract directly from
cininstead of going via astringand anistringstream: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 withcin.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).