linux 命令行輸入

linux 行輸入

程序如下

#include <stdio.h>
#include <iostream>
#include <string>
int main()
{
printf("output test\n");
//std::string str = "type string test";
//printf("%s\n", str.c_str());
//std::cin >> str;
//printf("%s\n", str.c_str());
char cBuf[1024];
gets(cBuf);
printf("%s\n", cBuf);
fgets(cBuf, 1024, stdin);
printf("%s\n", cBuf);
printf("program end\n");
return 0;
}

運行結果如下:

[root@localhost prog]# g++ input.c -o input
/tmp/cc5NnA6v.o(.text+0x2e): In function `main':
: the `gets' function is dangerous and should not be used.

[root@localhost prog]# ./input
output test
gets test
gets test
fgets test
fgets test
 
program end
[root@localhost prog]#


http://blog.csdn.net/zx824/article/details/6859930

今天在LINUX下編譯C程序時,出現了:
warning: the `gets' function is dangerous and should not be used.

這個warning。

百度之後,得知

問題出在程序中使用了 gets  ,Linux 下gcc編譯器不支持這個函數,解決辦法是使用 fgets


  1. fgets()函數的基本用法爲:  
  2.   
  3. fgets(char * s,int size,FILE * stream);//eg:可以用fgets(tempstr,10,stdin)//tempstr 爲char[]變量,10爲要輸入的字符串長度,stdin爲從標準終端輸入。  

  1. /*   代碼實現     */  
  2.   
  3. #include <stdio.h>  
  4. int main ( ) {  
  5.   
  6.    char name[20];  
  7.   
  8.    printf("\n 輸入任意字符 : ");  
  9.   
  10.    fgets(name, 20, stdin);//stdin 意思是鍵盤輸入  
  11.   
  12.    fputs(name, stdout); //stdout 輸出  
  13.   
  14.    return 0;  
  15. }  

根據以上改動後,果然沒有了warning,但是調試了n久的一個程序,確實怎麼也沒有正確結果,最後step跟蹤,才發現了問題所在!那就是:
gets從終端讀入是的字符串是用\0結束的,而fgets是以\n結束的(一般輸入都用ENTER結束),然後strcmp兩者的時候是不會相等的!

所以建議大家還是繼續讓它warning吧。。爲了正確性!


這個問題主要應該是因爲linux 和 windows的文件在換行符上編碼不一樣導致的,linux的換行是\0,windows的換行是\13\0,是兩個字符。

但是的文件應該是在windows下編譯的,所以導致會出現兩字符不匹配。建議可以在linux終端下,利用dos2unix filename,來將換行符處理一下,應該就OK了


發佈了0 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章