【问题标题】:gets() not declared in the scopeget() 未在范围内声明
【发布时间】:2018-03-13 05:45:19
【问题描述】:

我尝试了很多东西,但没有结果。我用过<cstdio> 但没有帮助。 我再次尝试使用 fget 但没有得到任何好的结果。我使用在线编译器http://rextester.com/l/cpp_online_compiler_gcc

#include <iostream>
#include <string.h>
#include<stdio.h>
#include<cstdio>
using namespace std;
int main() {
    bool check;
    char sntn[100],word[100],test[20];
    gets (word);
    gets (sntn);
    int j=0,count=0,val,k;
    check=true;
    while(check) {
        for(; sntn[j]==32; j++) {
            test[k]=sntn[j];
            k++;
        }
    }
    k=0;
    j+=1;
    val=strcmp(test,word);
    if(val==0)
        count++;
    if(sntn[j]==32) {
        j+=1;
        check=true;
    }
    if(sntn[j]=='\0')
        check=false;

    cout<<endl<<count;
    return 0;
}

错误:

source_file.cpp: In function ‘int main()’:
source_file.cpp:9:11: error: ‘gets’ was not declared in this scope
 gets (word);
           ^

【问题讨论】:

  • 我省略了stdio.h 并使用了一个cstdio,但仍然出现同样的错误。
  • 提示:您可以使用 AStyle 等免费程序在发布代码之前对其进行格式化。
  • 只需在命名空间std&lt;string&gt; 标头中使用stringgetline
  • @Cheersandhth.-Alf,对不起,我是 Stackoverflow 的新手,所以不知道 Astyle。
  • @Cheersandhth.-Alf 请详细说明

标签: c++ ubuntu g++


【解决方案1】:

std::gets() 已在 C++11 中弃用并在 C++14 中删除。在线编译器必须使用 C++14 或更高版本的语言。

更重要的是,gets 被认为是一个安全问题。即使编译器支持,也不要使用它。请改用std::fgets()

除非您需要使用 &lt;cstdio&gt; 标头中的函数,否则 std::string 有更好的替代方案。

  1. std::getline()
  2. std::istream::getline()

这些链接包含帮助您入门的示例代码。

【讨论】:

  • 问题标记为 C++。为什么不推荐std::getline 而不是fgets
  • 怎么用?如果您详细说明 fgets 的用法,将有很大帮助。我尝试过,但没有成功。
  • @ChandramauliChakraborty,点击链接。他们有示例代码可以帮助您入门。
猜你喜欢
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 2011-09-14
  • 2016-08-09
  • 2019-02-17
相关资源
最近更新 更多