Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a string value to a string variable in C++

Shouldn't this work?

string s;
s = "some string";
like image 359
neuromancer Avatar asked May 23 '10 23:05

neuromancer


People also ask

Can you assign a string to a variable in C?

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.

Can we assign string to string in C?

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 do you assign a string value to a variable?

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.

How do you assign a string to a string?

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.


1 Answers

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");
like image 121
sbi Avatar answered Sep 22 '22 11:09

sbi