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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM