为什么我不能使用字符串?

时间:2016-08-23 14:33:55

标签: c++ string cin

我有以下代码

#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;
}

我收到此错误

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;
                 ^

为什么我无法使用字符串?我用Cloud9运行它,对C ++来说相对较新。如何将cin的输入传输到字符串x

1 个答案:

答案 0 :(得分:4)

您必须指定命名空间:将string更改为std::string