There is a version of std::getline() which accepts std::string as target buffer. It is designed to take advantage of std::string's auto-resize capability and prevent overflows. Example from std::getline manpage:
#include <string>
#include <iostream>
int main()
{
// greet the user
std::string name;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello " << name << ", nice to meet you.\n";
}
In addition to the safety you asked about, std::string gives you also automatic memory management - so you don't need to remember to delete anything, which would be necessary in your example.
If you are not allowed to use std::string, you can use std::basic_istream::getline, which comes in two forms:
basic_istream& getline( char_type* s, std::streamsize count );
basic_istream& getline( char_type* s, std::streamsize count, char_type delim );
It allows you to specify max number of characters to read and an optional delimiter. std::basic_istream is the base class for std::istream. A very popular instance of this class is std::cin.
So basically, you can do:
char target[64];
std::cin.getline(target, 64);
std::stringinstead and make your life much simpler and your code easier to understand.cin.getline(name, size)documentation here