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


[cpp]  view plain copy
  1. fgets()函数的基本用法为:  
  2.   
  3. fgets(char * s,int size,FILE * stream);//eg:可以用fgets(tempstr,10,stdin)//tempstr 为char[]变量,10为要输入的字符串长度,stdin为从标准终端输入。  

[cpp]  view plain copy
  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值