Shouldn't this work?
string s;
s = "some string";
It is legal to initialize a string variable, like this. char example[100] = "First value"; However, it is not legal to assign string variables, because you cannot assign to an entire array. Furthermore, you cannot do comparisons like this.
C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.
How to create a string and assign it to a variable. To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable.
String assignment is performed using the = operator and copies the actual bytes of the string from the source operand up to and including the null byte to the variable on the left-hand side, which must be of type string. You can create a new variable of type string by assigning it an expression of type string.
Shouldn't this work?
string s; s = "some string";
Well, actually it's spelled std::string
, but if you have a using namespace std;
(absolutely evil) or using std::string;
(somewhat less evil) before that, it should work - provided that you also have a #include <string>
at the top of your file.
Note, however, that it is wasteful to first initialize s
to be an empty string, just to replace that value in the very next statement. (And if efficiency wasn't your concern, why would you program in C++?) Better would be to initialize s
to the right value immediately:
std::string s = "some string"
or
std::string s("some string");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With