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
- fgets()函数的基本用法为:
- fgets(char * s,int size,FILE * stream);//eg:可以用fgets(tempstr,10,stdin)//tempstr 为char[]变量,10为要输入的字符串长度,stdin为从标准终端输入。
- /* 代码实现 */
- #include <stdio.h>
- int main ( ) {
- char name[20];
- printf("\n 输入任意字符 : ");
- fgets(name, 20, stdin);//stdin 意思是键盘输入
- fputs(name, stdout); //stdout 输出
- return 0;
- }
根据以上改动后,果然没有了warning,但是调试了n久的一个程序,确实怎么也没有正确结果,最后step跟踪,才发现了问题所在!那就是:
gets从终端读入是的字符串是用\0结束的,而fgets是以\n结束的(一般输入都用ENTER结束),然后strcmp两者的时候是不会相等的!
所以建议大家还是继续让它warning吧。。为了正确性!
这个问题主要应该是因为linux 和 windows的文件在换行符上编码不一样导致的,linux的换行是\0,windows的换行是\13\0,是两个字符。
但是的文件应该是在windows下编译的,所以导致会出现两字符不匹配。建议可以在linux终端下,利用dos2unix filename,来将换行符处理一下,应该就OK了