C++ 编译代码时出错

C++ 编译代码时出错,c++,printf,declaration,C++,Printf,Declaration,编译此代码时,我收到未声明的字符串错误 #include <stdio.h> #include <stdlib.h> int main() { string names; printf("What is your name?\n"); scanf("%s", &names); printf("Your name is %s", names); return 0; } #包括 #包括 int main() { 字符串名; printf(“您叫什么名字?\n”

编译此代码时,我收到未声明的字符串错误

#include <stdio.h>
#include <stdlib.h>


int main()
{
string names;
printf("What is your name?\n");
scanf("%s", &names);

printf("Your name is %s", names);
return 0;
}
#包括
#包括
int main()
{
字符串名;
printf(“您叫什么名字?\n”);
scanf(“%s”、&name);
printf(“您的名字是%s”,名字);
返回0;
}

有人能告诉我为什么吗。非常感谢

您应该包括字符串标题:

#include <string>

此外,代码中不要混合C和C++。试着使用

std::cout
not
printf
cin/getline
not
scanf
,,因为std::string是在标题字符串中定义的,您没有包括在内,因为它的全名和正确名是std::string,而不仅仅是string。

您需要添加

#include <string>

参见.p/>如果您正在编写C++,则标准字符串类称为“代码> STD::String ,并在头<代码> <代码>中。但是,你通常不想使用<代码> Prtff < /C>或<代码> SCAFF < /Cord>,你可以使用C++ I/O:

#include <iostream>
#include <string>

int main()
{
    using namespace std;
    string names;
    cout << "What is your name?" << endl;
    getline(cin, names);
    cout << "Your name is " << names << endl;
}

但是请注意,除非您非常小心,
scanf
可能会溢出缓冲区并导致各种运行时错误。

您错过了包含
printf
scanf
定义的头文件。在代码中添加
#包括


另外,我认为代码在没有
返回0的情况下工作结尾的行。

包括
字符串
标题。并且像@taocp所说的那样添加
std
。另外,
printf
是一个不了解流的C函数。使用
cin
cout
而不是旧的C函数。您使用哪种编译器?特别是,将
std::string
对象(本例中的名称)作为参数传递给
printf
肯定无法按预期工作。@MatstPeterson这是我忽略的另一个要点。非常感谢。
using namespace std;
#include <iostream>
#include <string>

int main()
{
    using namespace std;
    string names;
    cout << "What is your name?" << endl;
    getline(cin, names);
    cout << "Your name is " << names << endl;
}
char names[SOME_LARGE_NUMBER];