c - 如何在我的 C 程序中多次使用“gets”函数?
问题描述
我的代码:
#include <stdio.h>
#include <math.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[10],b[10];
puts("enter");
gets(a);
puts("enter");
gets(b);
puts("enter");
puts(a);
puts(b);
}
return 0;
}
输出:
1
enter
enter
surya (string entered by user)
enter
surya (last puts function worked)
解决方案
如何在 C 程序中多次使用“gets”函数?
你永远不gets()
应该在你的程序中使用。它已被弃用,因为它会导致缓冲区溢出,因为它不可能停止消耗特定数量的字符 - fe 并且主要重要的是 - 缓冲区a
或b
每 10 个字符能够容纳的字符数量。
这里也解释了:
特别是,在乔纳森莱弗勒的这个回答中。
改为使用fgets()
。
此外,循环的定义a
和b
内部while
没有任何意义,即使很难,这只是一个玩具程序,用于学习目的。
此外请注意,这scanf()
会留下换行符,由按下从scanf()
调用中返回stdin
。你必须抓住这个,否则fgets()
之后的第一个会消耗这个角色。
这是更正后的程序:
#include <stdio.h>
int main()
{
int t;
char a[10],b[10];
if(scanf("%d",&t) != 1)
{
printf("Error at scanning!");
return 1;
}
getchar(); // For catching the left newline from scanf().
while(t--)
{
puts("Enter string A: ");
fgets(a,sizeof a, stdin);
puts("Enter string B: ");
fgets(b,sizeof b, stdin);
printf("\n");
puts(a);
puts(b);
printf("\n\n");
}
return 0;
}
执行:
$PATH/a.out
2
Enter string A:
hello
Enter string B:
world
hello
world
Enter string A:
apple
Enter string B:
banana
apple
banana
推荐阅读
- excel - 打开 CSV 文件而不将文本转换为公式
- ruby-on-rails - 寻找下载数据文件、从数据创建 txt 文件并发送到 AWS S3 的最佳方式?
- oop - 通过 UUID 存储对象的模式名称
- r - 如何将 Shiny 的输入结果插入到 mySQL where 子句?
- prolog - 列表中的相同元素
- javascript - PHP echo Javascript函数不做任何事情
- java - 主数据源中没有名为“entityManagerFactory”的bean
- amazon-web-services - 当 cloudwatch 日志触发 Lambda 时重启 EC2 实例
- r - ggplot:在y轴行名中创建换行符
- node.js - “npm install ejs --save”在 GitBash 上不起作用,但在 windows powershell 上使用时有效