-1

I have the below code

#include <iostream>
#include <string>

main(){
    std::cout << "What's Your Name? ";
    string x = "";
    std::cin >> x;
    std::cout << std::endl << "Nice to meet you " << x << "!" << std::endl;
}

And am getting this error

Running /home/ubuntu/workspace/client.cpp
/home/ubuntu/workspace/client.cpp: In function ‘int main()’:
/home/ubuntu/workspace/client.cpp:6:5: error: ‘string’ was not declared in this scope
     string x = "";
     ^
/home/ubuntu/workspace/client.cpp:6:5: note: suggested alternative:
In file included from /usr/include/c++/4.8/iosfwd:39:0,
                 from /usr/include/c++/4.8/ios:38,
                 from /usr/include/c++/4.8/ostream:38,
                 from /usr/include/c++/4.8/iostream:39,
                 from /home/ubuntu/workspace/client.cpp:1:
/usr/include/c++/4.8/bits/stringfwd.h:62:33: note:   ‘std::string’
   typedef basic_string<char>    string;   
                                 ^
/home/ubuntu/workspace/client.cpp:6:12: error: expected ‘;’ before ‘x’
     string x = "";
            ^
/home/ubuntu/workspace/client.cpp:7:17: error: ‘x’ was not declared in this scope
     std::cin >> x;
                 ^

Why am I not able to use a string? I'm running it with Cloud9, and am relatively new to C++. How can I transfer the input of cin to the string x?

baranskistad
  • 2,176
  • 1
  • 21
  • 42

1 Answers1

4

You must specify the namespace: change string to std::string

Smeeheey
  • 9,906
  • 23
  • 39
  • 2
    Addition: Thats because `string` as such doesn't exist in native C++ and can only be used because it is defined in ``. Because there it is located in the `std` namespace, you have to write std::string instead of string. You CAN indeed make a typedef (`typedef string std::string`) or use a define: `#define STRING std::string` – Tom Doodler Aug 23 '16 at 14:36
  • 2
    ...or you could use `using std::string` – jaggedSpire Aug 23 '16 at 14:37
  • I've never seen that in C++ but the more you know... thx – Tom Doodler Aug 23 '16 at 14:38
  • Don't forget @bjskistad , that you should also be writing `int main()` not just main, it is considered bad code. – Arnav Borborah Aug 23 '16 at 14:42