我才刚刚开始我的编程之旅。我在 Ubuntu 终端中编码。我在编译使用该gets()函数的程序时遇到问题。
#include<stdio.h>
/*example of multi char i/p function*/
void main()
{
char loki[10];
gets(loki);
printf("puts(loki)");
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
warning: 'implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
Run Code Online (Sandbox Code Playgroud)
在 Ubuntu 上,man gets在终端中运行。它应该向您显示此gets(3)手册页。
该文件用书面英语指出:
切勿使用此功能。
更一般地说,在编程之前,请阅读文档。对于 Linux 上的 C,请考虑阅读手册页、此C 参考、许多 C 编程教程和 C11 标准n1570。
英文维基百科也提到gets
最后,
警告:'函数'gets'的隐式声明;您指的是 'fgets' 吗?[-Wimplicit-function-declaration]
对我来说似乎很清楚,因为用英文写的。根据经验,确保您的程序编译时没有警告。另请阅读如何调试小程序。
您可能对理解缩写词RTFM 和 STFW 感兴趣。
我学习了 C 和 Unix 编程(1985 年),从第 1 节到第 9 节阅读 SunOS3 手册页(当时是纸上的,在工作中,与我当时有特权使用的 Sun3/160 工作站一起出售)。
您可以在手册页之前阅读Advanced Linux Programming。
我才刚刚开始我的编程之旅。
然后我推荐阅读SICP。在我爷爷眼里,它仍然是最好的编程入门,即使是在 2019 年。另见这些提示。SICP 是否使用一些在专业现实生活中不太常用的编程语言并不重要(但请查看Guile):编程是关于概念的,而不是关于编码的。您将通过 SICP 学习的概念肯定会帮助您以后编写更好的 C 代码。当然阅读http://norvig.com/21-days.html
注意。我是法国人(出生于 1959 年),所以母语不是英语。但是我被教导阅读,包括在我攻读博士学位期间,当然还有在高中和我自己的父母。当我在大学教一些 CS 东西时,我告诉学生的第一件事就是阅读。永远不要以阅读为耻。
gets在 C11 中被移除,因为无法正确使用. gets不知道它可以存储多少个字符到数组中并继续写入用户提供的尽可能多的字符,这会导致程序出现未定义的行为- 崩溃、修改无关数据等。
解决方法是fgets改用,但请记住,它会在缓冲区中留下一个换行符:
#include <stdio.h>
// example of multi char i/p function
int main(void)
{
char loki[10];
fgets(loki, 10, stdin);
// now loki will have the new line as the last character
// if less than 9 characters were on the line
// we can remove the extra with `strcspn`:
loki[strcspn(loki, "\n")] = 0;
// this will print the given string followed by an extra newline.
puts(loki);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5969 次 |
| 最近记录: |