我在编译此代码时未声明此错误字符串。
#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;
}
谁能告诉我为什么。非常感谢
我在编译此代码时未声明此错误字符串。
#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;
}
谁能告诉我为什么。非常感谢
你应该包括字符串标题:
#include <string>
并且在使用时不要忘记命名空间std
:
std::string names;
此外,不要在编写代码时混合使用 C 和 C++。尝试使用std::cout
not printf
,cin/getline
not scanf
。
如果您正在编写 C++,则调用标准字符串类std::string
,并且位于 header 中<string>
。但是你通常不想使用printf
它scanf
,你会使用 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;
}
如果(尽管有问题标签)您正在编写 C,那么就没有称为string
. 字符串通常由字符数组表示:
char names[SOME_LARGE_NUMBER];
但请注意,除非您非常小心,否则scanf
可能会超出缓冲区并导致各种运行时错误。
因为 std::string 是在您没有包含的标题字符串中定义的,并且因为它的全名和正确名称是 std::string,而不仅仅是字符串。
您错过了包含printf
和定义的头文件scanf
。添加#include <string.h>
到代码中。
另外,我认为代码return 0;
在最后没有行。