[英]C++ std::getline error
我是 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;
}
谢谢!
错误不是来自std::getline
。 错误是您需要使用std::string
除非您使用using namespace std
。 还需要std::endl
。
您需要在该命名空间中的所有标识符上使用std::
。 在这种情况下, std::string
和std::endl
。 你可以在getline()
上不用它,因为 Koenig 查找会为你处理这个问题。
#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;
行。)
试试这个:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.