3

我在编译此代码时未声明此错误字符串。

#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;
}

谁能告诉我为什么。非常感谢

4

5 回答 5

8

你应该包括字符串标题:

#include <string>

并且在使用时不要忘记命名空间std

std::string names;

此外,不要在编写代码时混合使用 C 和 C++。尝试使用std::coutnot printfcin/getlinenot scanf

于 2013-06-20T14:47:39.657 回答
3

您需要添加

#include <string>

从 C++ 标准库中引用字符串并声明您正在使用 std

using namespace std;

这里

于 2013-06-20T14:49:21.583 回答
2

如果您正在编写 C++,则调用标准字符串类std::string,并且位于 header 中<string>。但是你通常不想使用printfscanf,你会使用 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可能会超出缓冲区并导致各种运行时错误。

于 2013-06-20T14:51:27.307 回答
0

因为 std::string 是在您没有包含的标题字符串中定义的,并且因为它的全名和正确名称是 std::string,而不仅仅是字符串。

于 2013-06-20T14:47:50.830 回答
0

您错过了包含printf和定义的头文件scanf。添加#include <string.h>到代码中。

另外,我认为代码return 0;在最后没有行。

于 2013-06-20T14:51:29.000 回答