I recently had an assignment that asked us to restrict the amount of characters a user can enter for his or her name. My professor said this is useful in the event that your program is being "attacked." The simplest solution was to use C strings:
#include <iostream>
const int MAX_NAME_SIZE = 15;
int main () {
char name[MAX_NAME_SIZE];
std::cin.getline(name, MAX_NAME_SIZE);
std::cout << name << std::endl;
return 0;
}
However, I wanted to use C++ strings instead. Unfortunately this requires some unorthodox (to me at least) methods:
#include <iostream>
#include <string>
const int MAX_NAME_SIZE = 15;
int main () {
std::string name(' ', MAX_NAME_SIZE);
name.reserve(MAX_NAME_SIZE);
std::cin.getline(const_cast<char *>(name.data()), MAX_NAME_SIZE);
// optionally you could use the gcount function here to downsize the string
std::cout << name << std::endl;
return 0;
}
So my questions are:
- Why was the functionality of the
istream getline
not included in thestring getline
? - Is there another, preferably better, way of doing this with C++ strings?
- Is there another, once again better, way of doing this at all?
- Since the input buffer is pretty big, does it really slow the program down that much to prevent you from just using the
resize()
member function?
Any side comments are welcome.
Thanks,
Arkinder