Is there any way to get complete sentence with space as input from the user in char pointer (Not in the char array and not in the string) in c++? [duplicate]
Solution 1:
In the main
function you have the definition
char* szString;
That tells the compiler that szString
is a pointer to characters. But you don't make that pointer actually point to anything.
So when you use it to get input, the input operation will write the input to some unknown location. This is undefined behavior, and will cause your program to behave unexpectedly, including crashing.
Either you have to make the pointer point to some valid location. Or even better, don't use pointers for strings, use std::string
.
Solution 2:
char* szString;
cin >> szString;
This code doesn't do what you might think it does! To input a string from cin
use:
std::string s;
cin >> s;
Change further occurences of char*
to std::string
, std::string&
accordingly.