C++ “字符串”未声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16290644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:13:27  来源:igfitidea点击:

`string' undeclared

c++

提问by amartin94

Writing my first program, and my using namespace std;statement won't work. When I build the program I'm getting thrown this error:

编写我的第一个程序,我的using namespace std;语句不起作用。当我构建程序时,我抛出了这个错误:

C:\Users\p6735a\Desktop\Project\game.cpp: In function `int main(int, char *)':
C:\Users\p6735a\Desktop\Project\game.cpp:6: `string' undeclared (first use this         function)
C:\Users\p6735a\Desktop\Project\game.cpp:6: (Each undeclared identifier is reported only once
C:\Users\p6735a\Desktop\Project\game.cpp:6: for each function it appears in.)
C:\Users\p6735a\Desktop\Project\game.cpp:6: parse error before `;'
[Finished in 0.1s with exit code 1]

Here's the code:

这是代码:

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    string input;
    int hp;

    cout << "You see a man. Would you like to kill him?\n1. Yes\n2. No" << endl;
    //cin >> input;
}

回答by 0x499602D2

You need to include the string header:

您需要包含字符串标题:

#include <string>

But why have a using namespace stddeclaration at all? Simply use the objects individually:

但是为什么要using namespace std声明呢?只需单独使用对象:

using std::cout;
using std::string;

回答by taocp

Add

添加

#include <string>

to your includes since stringis from <string>header.

到您的包含,因为string来自<string>标题。

Meanwhile, it is bad practice to use using namespace std(see Why using namespace std is considered a bad practice), you'd better use:

同时,使用是不好的做法using namespace std(请参阅为什么使用命名空间 std 被认为是不好的做法),您最好使用:

std::string input
std::cout, std::endl

instead.

反而。

回答by SilverFang

In Visual Studio you need to have the new #include "pch.h".

在 Visual Studio 中,您需要拥有新的#include "pch.h".