7

Shouldn't this work?

string s;
s = "some string";
ZachB
  • 13,051
  • 4
  • 61
  • 89
neuromancer
  • 53,769
  • 78
  • 166
  • 223
  • 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. – sbi May 23 '10 at 23:58

3 Answers3

14

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");
sbi
  • 219,715
  • 46
  • 258
  • 445
  • well sometimes that is not possible. (like when you know the value of the string way after you declare it) – KansaiRobot Oct 25 '21 at 00:18
  • @KansaiRobot (_Note:_ Local variables are _defined_. Yes, [a definition is a declaration](https://stackoverflow.com/a/1410632/140719), 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.) – sbi Jan 10 '22 at 15:31
10

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?)

Stephen
  • 47,994
  • 7
  • 61
  • 70
  • 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. – neuromancer May 24 '10 at 00:04
  • 3
    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 :) – Stephen May 24 '10 at 00:07
-2

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

  • 1
    `` is not for `std::string`. And `bits/…` is problematic too. Finally, using `.assign()` changes exactly nothing. – Deduplicator Oct 27 '18 at 19:46