2013-11-27 106 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;线的包括后)。