You have not allocated any memory to str
. So you are trying to essentially write to a pointer which cannot hold the string. Essentially this leads to an Undefined Behavior and a seg fault.
The solution is:
You should use std::string instead of pointer.
std::string str;
std::cout<<"please enter string : ";
std::cin >>str;
Also, try not to mix C and C++.
Use streams
in C++ not printf
Alternatively, there are 2 other approaches:
Not so good other Approach 1:
You can allocate memory to str
by making it an fixed size array:
#define MAX_INPUT 256
char str[MAX_INPUT]={0};
Drawback:
This would require that you need to know the length of the maximum input that user can enter at compile time, Since Variable Length Arrays are not allowed in C++.
Not so good other Approach 2:
You could allocate memory dynamically to str
using new []
.str
will be a pointer in this case.
#define MAX_INPUT 256
char *str = new char[MAX_INPUT];
Drawback:
Again this approach has the drawback of knowing how much memory to allocate at compile time in this case,since user inputs the string. Also, You need to remember to deallocate by calling delete[]
or you leak memory.
Also, try to avoid using new
as much as possible in C++.
Conclusion:
Best solution here is to use std::string
because it saves you from all above problems.