我是C ++的新手,有人可以向我解释为什么我在使用“std :: getline”时收到以下错误?这是代码:
#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;
}
谢谢!
答案 0 :(得分:8)
错误不是来自std::getline
。除非您使用std::string
,否则您需要使用using namespace std
。还需要std::endl
。
答案 1 :(得分:4)
您需要对该命名空间中的所有标识符使用std::
。在这种情况下,std::string
和std::endl
。你可以在getline()
没有它的情况下离开,因为Koenig查找会为你解决这个问题。
答案 2 :(得分: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::
并在包含后添加using namespace std;
行。 )
答案 3 :(得分:0)
尝试一下:
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Enter your entire name (first and last)." <<
std::endl;
while(getline(std::cin, name))
{
std::cout <<"Your name is:"<< name << '\n';
}
return 0;
}