【问题标题】:"gets() was not declared in this scope" error [duplicate]“gets() 未在此范围内声明”错误 [重复]
【发布时间】:2016-02-07 05:47:25
【问题描述】:

使用以下代码,我得到“gets() 未在此范围内声明”错误:

#include <iostream>
#include <string.h>
using namespace std;

int main()
{

   // string str[]={"I am a boy"};

   string str[20];`

   gets(str);

   cout<<*str;

   return 0;
}

【问题讨论】:

  • 阅读gets manual。它告诉您需要包含哪个头文件。但请注意它在结尾处所说的内容:“永远不要使用gets()。因为事先不知道数据是不可能知道gets() 将读取多少个字符,并且因为gets() 将继续存储字符超过缓冲区的末尾,使用它非常危险。它已被用来破坏计算机安全性。请改用 fgets()。"

标签: c++


【解决方案1】:

函数 std::gets() 在 C++11 中已弃用,并从 C++14 中完全删除。

【讨论】:

    【解决方案2】:

    由于 gets() 是一个 C 风格的函数,所以如果你需要在你的 c++ 代码中包含它,那么你需要包含名为 stdio.h 的头文件,而且你只能将一个 c 风格的字符串传递给 gets() 函数不是 C++ 字符串类。 因此,在您的代码稍作修改后,它变为:

    #include <iostream>
    #include <string.h>
    #include "stdio.h"
    using namespace std;
    
    int main()
    {
    
    // string str[]={"I am a boy"};
    
    char str[20];`
    
     gets(str);
    
     printf("%s",str);
    
    return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      相关资源
      最近更新 更多