我正在试着解决这个问题。我接受字符作为输入并使用gets()。但是函数显示了上面提到的错误。
我不知道为什么这个函数表现不佳。请帮我找出故障。我是个初学者。
如前所述,错误消息是:
Use of undeclared identifier 'gets'我的C++代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
char line[1000];
bool open = true;
while (gets(line)) //***in this line gets() is showing error***
{
int len = strlen(line);
for (int i = 0; i < len; i++)
{
if (line[i] == '"')
{
if (open)
{
printf("``");
}
else
{
printf("''");
}
open = !open;
}
else
{
printf("%c", line[i]);
}
}
printf("\n");
}
return 0;
}

发布于 2020-09-12 18:51:32
std::gets在C++11中被弃用,并从C++14和this a dangerous function and it should never be used中删除,尽管一些编译器仍然提供它,但它看起来不适合您的情况,这是一件好事。
您应该使用类似于std::getline的内容,请注意,为此您需要将line参数设置为std::string。
string line;
//...
while (getline(cin, line)){
//...
}或者,如果您确实需要char数组,则可以改用fgets:
char line[1000];
//...
while(fgets(line, sizeof line, stdin)){
//remove newline character using strcspn
line[strcspn(line, "\n")] = '\0';
//or with C++ std::replace
replace(&line[0], &line[1000], '\n', '\0'); //&line[1000] one past the array end
//...
}附注:
以not using using namespace std;和#include 为例,请访问链接以获取详细信息。
发布于 2020-09-12 19:07:56
正如前面提到的,gets()已被弃用。阅读关于它的here
但是让我们来看看为什么你首先得到这个错误的根本原因。一个
未声明的标识符“gets”
错误是因为编译器找不到您正在使用的函数的声明。在本例中,get()是在stdio.h中定义的
我还看到您按照建议使用了std::getline(),因此需要包含string头。
看一看我提到的两个链接,以了解正确的用法。
https://stackoverflow.com/questions/63859484
复制相似问题