I wanted to declare an array with a pointer in character type, and the length of the array can be determined by my input string.
I wrote it in this way:
char *s;
cout << "Enter a string: " << endl;
cin >> s;
I expected that I can initialize the string by the cin
operation, but an error showed up when compiling. The error is about "invalid operands to binary expression".
I'm not sure why the lines I wrote was wrong.
I though not only the built in string
class is used for declaring an array.
Isn't the string
data type in C the same as "a character array"?
Isn't the line char *s
means the pointer s
points to an character array (or string)?
Thank you!
CodePudding user response:
You should use std::string
.
It is a class that represents a string of characters. It is different than an old c style array of characters (although internally might contain one).
In your case:
#include <string>
#include <iostream>
std::string s;
std::cout << "Enter a string: " << endl;
std::cin >> s;
Using std::string
means memory is managed automatically for you. Specifically with cin
it will also be resized to fit the input.
A side note: better to avoid using namespace std
- see here Why is "using namespace std;" considered bad practice?.
CodePudding user response:
"the cin operation".
cin
is really the source. The real work is done by the overloaded operator>>
. And the operator>>
which reads to a char*
expects that the char*
is already allocated to the right size. That's of course a problem with cin
, where the size is unknown.
The operator>>
overload that reads to std::string
will resize the std::string
to the right size.
CodePudding user response:
The answer to your question is no, as when you create a type pointer you always have to specify in advance how much memory to allocate. We can imagine that this is what happens with strings, that is to go to fetch the data and arrange the occupied cells in memory at a later time.
Now the real problem is, it is true that you have declared a pointer to a character, but you have not specified how much to allocate for it. It is as if you are saying you want to create a box but you are not specifying the size. I show you the correct method:
char *s = new char[10];
Obviously when using pointers, always remember to deallocate them at the end of use so as not to have any memory leaks.
Taking a summary of the situation, you tried to save a data in a box that you intend to create but does not exist. That is, you have named the box called s
which will contain a pointer to a character
but you have not yet built/created it in its final size.