1

I'm fairly new to C++ and I'm currently learning about strings.

So, I'm familiar with this way of creating a string from Java:

string text = "hello";

Now, I see something like:

 std::string text("hello");

So, the second one looks kind of difficult to read because I didn't know what the :: meant.

  1. Why are there two ways to build strings?

  2. What are the differences between them?

  3. What situations would let me prefer to use one way rather the than the other?

tenkii
  • 439
  • 2
  • 10
  • 22
  • `So, I'm familiar with this way of creating a string from Java:` Pretend Java doesn't exist. What you're asking are basic C++ questions that can be answered by most introductory books on C++. – PaulMcKenzie Aug 30 '14 at 23:59
  • 1
    I have no idea where you saw that second line, but there is nothing named `std::str` in standard C++. – Benjamin Lindley Aug 31 '14 at 00:01
  • `string text = "hello";` this is not java this is c++. ` std::str("hello");`where did you see this? Look in a book. – Captain Giraffe Aug 31 '14 at 00:01
  • 1
    `::` is just the namespace separator token in C++. It is similar to how you separate package/type names in Java with `.`. – cdhowie Aug 31 '14 at 00:05
  • 1
    It's been a long time since I programmed in Java, but I'm pretty sure it had the *assignment operator* and *constructors*, just like you see here. – indiv Aug 31 '14 at 00:18
  • This is actually two questions (at least). I've marked it as a duplicate of the question which is about the different methods of initialization. That post doesn't answer the part about the double colon though. That is a much simpler problem and is answered here: http://stackoverflow.com/questions/3480320/what-does-the-mean-in-c – Benjamin Lindley Aug 31 '14 at 00:27

1 Answers1

0

First of all you need to import the string header and the standard iostream header

#import<iostream>
#import<string>

using namespace std;

int main(){
    string output = "Hello World!";
    cout<<output<<endl;
}

What this block of code does is set the value output to "Hello World!" and then you output it to the console using "cout"

You wouldn't need to use the std:: if you were using the standard namespace as you can see in the 3rd line of code.

Adithya
  • 63
  • 1
  • 8
  • 1
    Note that [`using namespace std;` is considered bad practice](http://stackoverflow.com/q/1452721/501250). – cdhowie Aug 31 '14 at 00:33
  • he said he was a beginner and so most beginners don't use different libraries.. as he moves on he will tend to use std::cout or std::cin – Adithya Aug 31 '14 at 02:01
  • Old habits die hard. Better to instill good habits early. – cdhowie Aug 31 '14 at 02:50