-4

I am completely confused about a taking an string input in C++.

char str[4];
cin>>str;
cout<<str;

works. but the

char* str;
cin>>str;
cout<<str;

doesn't work. why?

user156327
  • 1
  • 4
  • 32
  • 56
Delsa
  • 193
  • 1
  • 1
  • 10

2 Answers2

6

because in the second case, no memory is allocated: you're writing to undefined memory area => UB (likely: SEGV)

You could do str=new char[4];, but if you input more than 3 characters you have a buffer overflow problem as well, and since you cannot control what the user inputs, you cannot ensure that it won't happen.

(could also happen in your first working case of course)

So, since you're using C++, I'd suggest to use std::string like this:

std::string str;
cin>>str;
cout<<str;

no more char * or arrays, no more allocation, memory leaks...: real C++. You can still get the const char * representation of the object using str.c_str() when you want to interface with C functions.

You can also concatenate string objects like this: a + b, as opposed to the dreaded strcat, and the list goes on and on...

I could dabble for hours on how string is better than char, or I could link to other answers like those:

Community
  • 1
  • 1
Jean-François Fabre
  • 126,787
  • 22
  • 103
  • 165
0

As Jean-François Fabre said you can use std::string to achieve your goal.

Just in case you wanted to use pure C syntax and char arrays (with a fixed size N - in your case 3) you might go with something like that:

#define N 3
char str[N + 1];
fgets(str, sizeof(str), stdin);

This makes sure that you won't encounter an overflow.

moped
  • 4,218
  • 2
  • 14
  • 37