Reputation: 651
I have an object with a std::string
field notes
that allows a maximum of 100 chars. I need to write a C++ console interface (using IOStream
) to let the user input these notes. All characters are allowed, including of course spaces.
What's the best way of doing such thing?
Is there a way to let the user know how many characters are left?
EDIT: Also empty string should be allowed
Upvotes: 0
Views: 1480
Reputation: 145457
Use std::string
and std::getline
.
You can display one hundred asterisks this way:
cout << " " << string( 100, '*' ) << endl;
cout << "> "; getline( cin, line );
then, with a sufficiently wide console window, the user can see how much space remains.
Upvotes: 1
Reputation: 1
I'm not sure that std::string
can be strongly limited in its capacity (the max_size
member function gives a big number). If you really want to limit to 100 characters (which is not a very good thing to do), using a char buf[100];
(or perhaps a std::array
) could make more sense (but don't forget to have a terminating null character).
And to input that field, you may want to use the getline member function of your input stream.
If you are coding on Linux a console application, the ncurses library could be useful to you. Or perhaps the readline library
Upvotes: 0