gets导致编译失败,并出现“使用未声明的标识符'gets'”错误

问题描述

我正在尝试解决e问题。我将字符作为输入并使用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;
}

enter image description here

解决方法

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 <bits/stdc++.h>,请单击链接以获取详细信息。

,

这是更正。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string line;
    bool open = true;
    while (getline(cin,line))
    {
        int len = line.length();
        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;
}
, 如前所述,不赞成使用

gets()。阅读有关here

但是让我们弄清楚为什么首先出现错误的根本原因。

未声明的标识符“获取”

错误是因为编译器找不到正在使用的函数的声明。在您的情况下,get()是在stdio.h中定义的。

我还看到您按照建议使用std::getline(),为此您需要包含System.in标头。

看看我提到的2个链接,以了解正确的用法。