7

Shouldn't this work?

string s;
s = "some string";
1
  • 2
    @David: I agree that the question is somewhat terse, but for all we know Phenom could have tried and got an error message: int main() { string s; s = "some string"; } will give error messages which might seem cryptic to a novice. Commented May 23, 2010 at 23:58

3 Answers 3

13

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");
Sign up to request clarification or add additional context in comments.

3 Comments

well sometimes that is not possible. (like when you know the value of the string way after you declare it)
@KansaiRobot (Note: Local variables are defined. Yes, a definition is a declaration, too. But then, while we are apes, too, and mammals, and vertebrates, etc., we still think and speak of ourselves as humans.) If you do not know the value to initialize a string with, define the string later, if possible. (If it is not possible, then that's what default constructors are there for.)
"don't do this for efficiency" is not useful when talking about toy examples that have been simplified
11

Yes!

It's default constructing a string, then assigning it from a const char*.

(Why did you post this question?... did you at least try it?)

2 Comments

I was having a problem doing it with vectors. This answer helped me to find the problem, which lay elsewhere, and had to do with how vectors work.
Ah, I see - glad it helped. Next time, you might post a little more detail about your problem and we'd probably enjoy helping you with that too :)
-2

use header file string.h or bits/stdc++.h then try s.assign("some string");

1 Comment

<string.h> is not for std::string. And bits/… is problematic too. Finally, using .assign() changes exactly nothing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.