码迷,mamicode.com
首页 > 系统相关 > 详细

linux下使用gcc/g++编译代码时gets函数有错误

时间:2016-03-13 12:40:16      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

今天在linux中使用个g++编译一个名为myfirst.cpp的代码的时候,出现如下错误

myfirst.cpp: In function ‘int main()’:
myfirst.cpp:11:2: warning: ‘char* gets(char*)’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
gets(cc);
^
myfirst.cpp:11:9: warning: ‘char* gets(char*)’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
gets(cc);
^
/tmp/ccoHyVHf.o: In function `main‘:
myfirst.cpp:(.text+0xad): warning: the `gets‘ function is dangerous and should not be used.
/tmp/ccoHyVHf.o: In function `__static_initialization_and_destruction_0(int, int)‘:
myfirst.cpp:(.text+0x103): undefined reference to `std::ios_base::Init::Init()‘
myfirst.cpp:(.text+0x112): undefined reference to `std::ios_base::Init::~Init()‘
collect2: error: ld returned 1 exit status

仔细看错误信息得知,gets函数是危险的,具体信息请百度或者google,但是我用gets函数目的仅仅是为了输入一串字符,系统的用不了,我就自己写一个

ps:以下操作都实在linux的终端中进行,系统版本为ubuntu 14.04 LTS

打开终端(ctrl+Alt+T)

touch cstdio//创建文件cstdio,我使用的是C++

vim cstdio//编辑cstdio,并添加以下内容

#include<cstdio>
void mygets(char *str)
{
  int i=0;
  scanf("%c",&str[i]);
  while(str[i++]!=‘\n‘)
  {
    scanf("%c",&str[i]);
  }
  str[i-1]=0;//  \0是字符数组中默认的字符串结尾,\0所对应的ascii码为0
}

 

这样自己的库函数就写好了,我不知道标准的库函数具体什么样,但是肯定不是我这样,嘿嘿

使用的时候,在头文件位置加上

#include"cstdio"  //是双引号,而不是尖括号

mygets(str);  //str书字符数组名

就可以在linux下间接使用gets函数了

若是使用C语言的写法的话,将

cstdio 文件的文件名

改为

stdio.h,将该文件的里面的

#include<cstdio>

改为

#include<stdio.h>

 

本文首发地址

https://www.textarea.com/suppermary/linux-xia-shiyong-gcc-g-bianyi-daima-shi-gets-hanshu-you-cuowu-564/

linux下使用gcc/g++编译代码时gets函数有错误

标签:

原文地址:http://www.cnblogs.com/hushuangpu/p/5271464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!