2016-08-23 74 views
-2

我有下面的代碼爲什麼我不能使用字符串?

#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

+8

'的std :: string'不'string' – jaggedSpire

+1

附註:這是'INT主要()',裸機'的main()'是[生病 - 形式](http://stackoverflow.com/questions/331148/does-c-allow-default-return-types-for-functions) – dhke

+1

對於這樣的小項目,你可以做一個'使用命名空間標準;'右包括之後。 – sp2danny

回答

4

您必須指定命名空間:改變stringstd::string

+2

此外:這是因爲''字符串本身不存在於本機C++中,只能使用,因爲它在''中定義。因爲它位於'std'命名空間中,所以必須寫入std :: string而不是string。你確實可以做一個typedef('typedef string std :: string')或者使用define:'#define STRING std :: string' –

+2

...或者你可以使用'std :: string' – jaggedSpire

+0

我從來沒有看到在C++中,但你知道得越多... thx –

相關問題