2013-11-27 103 views
0

我是C++的新手,有人請向我解釋爲什麼當我使用「std :: getline」時,我收到了以下錯誤?這裏是代碼:C++ std :: getline error

#include <iostream> 
#include <string> 

int main() { 

    string name; //receive an error here 

    std::cout << "Enter your entire name (first and last)." << endl; 
    std::getline(std::cin, name); 

    std::cout << "Your full name is " << name << endl; 

    return 0; 
} 


ERRORS: 
te.cc: In function `int main()': 
te.cc:7: error: `string' was not declared in this scope 
te.cc:7: error: expected `;' before "name" 
te.cc:11: error: `endl' was not declared in this scope 
te.cc:12: error: `name' was not declared in this scope 

但是,當我使用「getline」和「using namespace std;」時,程序將運行並編譯。而不是std :: getline。

#include <iostream> 
#include <string> 

using namespace std; 

int main() { 

    string name; 

    cout << "Enter your entire name (first and last)." << endl; 
    getline(cin, name); 

    cout << "Your full name is " << name << endl; 
    return 0; 
} 

謝謝!

回答

8

錯誤不是從std::getline。錯誤是您需要使用std::string,除非您使用using namespace std。還需要std::endl

4

您需要在該命名空間的所有標識符上使用std::。在這種情況下,std::stringstd::endl。您可以在getline()之外離開,因爲Koenig查找爲您提供幫助。

1
#include <iostream> 
#include <string> 

int main() 
{ 
    std::string name; // note the std:: 

    std::cout << "Enter your entire name (first and last)." << std::endl; // same here 
    std::getline(std::cin, name); 

    std::cout << "Your full name is " << name << std::endl; // and again 

    return 0; 
} 

你只需要聲明的是在std命名空間中各種元素的名稱空間(或者,你可以刪除所有std:: S和放置using namespace std;線的包括後)。