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

今天在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,并添加以下内容

int myown_gets(char *str)
{
int i=0;
char c;
while(scanf("%c",&c)&&(c=='\0'||c=='\n'));//这儿是用来吸收在myown_gets之前的残留在输入流中的回车用的
str[i++]=c;
while(scanf("%c",&c)&&(c!='\0'&&c!='\n'))
{
str[i++]=c;
c=0;
}
str[i]=0;
return i;
}

 

 

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

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

#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/

posted @ 2016-03-13 11:16  SupperMary  阅读(5462)  评论(0编辑  收藏  举报