When you declare nm
you don't initialize it, that means the value of nm
is indeterminate, it doesn't really point anywhere (in reality it points to a seemingly random location). You need to make it point to something big enough to hold the string you input.
Using uninitialized variables, and NULL
pointers, leads to undefined behavior whose most common result is a crash.
To fix this, either make it point to an already initialized array:
char str[20];
char* nm = str;
Or allocate memory for the string dynamically:
char* nm = new char[20];
Or even better, don't use character pointers as string, and especially not the gets
function (it's dangerous and have even been removed from the C standard), use the C++ std::string
class instead and std::getline
function to fetch a line:
std::string nm;
std::getline(std::cin, nm);
Or if you just want to get a single space-delimited word, use the normal input operator:
std::string nm;
std::cin >> nm;