You are free to look at this.
I don't normally tell people to do this, but the only reason I make an exception today is because this is the 36th post on this thread. And at this point you are just now starting to take the very first suggestion you were given all the way back in post #2 on this thread; feel free to kick yourself.
This may be another option for you. I'm not gonna bother explaining too much, since this is really simple code.
If you have specific needs then roll your own. The standard IO functions are building blocks, not your personal toolbox of goodies.
Code:#include <iostream> #include <ostream> #include <cstring> using std::cout; using std::cin; using std::endl; int main () { const std::streamsize MAX = 17; char buffer[MAX]; const std::streamsize oldw = cin.width(); cin.width( MAX ); cout << "Enter 16-character phrase: "; cin >> buffer; if ( cin.peek() != '\n' || std::strlen( buffer ) < MAX - 1 ) { cin.ignore( (unsigned)-1 ); //ignore any extraneous stuff cout << "Invalid phrase, try again\n"; } else { cin.ignore(); //ignore newline cout << "You entered \"" << buffer << "\"" << endl; } cin.width( oldw ); //copy buffer, do whatever }
Last edited by whiteflags; 10-15-2008 at 07:58 PM.
Is there a way to limit the number of characters getline accepts? I know that std::string simply grows as large as it needs, but this could lead to denial of service attack through resource exhaustion if there is no way to limit. Also, is there a way to get the count of elements actually read?
All I know is that you can't. (TBH, I don't see worrying about a DOS as useful here, since if they can throw 4G characters at your C++ program, they can throw 4G characters at your C program just as well with the same result; you're going to run into the maximum length of stdin well before that anyway, I should think.)
Okay, thanks for the help everyone. I think the lesson I'm taking home from this is don't program in C++ anymore if I ever want to have secure console input.
Did I miss something important? Why was my snippet insufficient to your needs?