c - C程序不在结构中打印字符串
问题描述
我制作了一个程序来将多个输入作为字符串,存储和打印它们。不知何故,存储在其中的“帐号”a[i].acn
没有打印。我试过调试,问题似乎出在将空格添加到a[i].name
.
#include <stdio.h>
#include <string.h>
struct Bank
{
char name[10],acn[8];
float bal;
}a[100];
int n,i,flag;
void add()
{
//function to add Rs. 100 to accounts that have balance over 1000
//and print the details.
for(i=0;i<n;i++)
if(a[i].bal>=1000)
a[i].bal+=100;
printf("\nS.No.\tName\t\tAcc. No.\tBalance(in Rs.)");
for(i=0;i<n;i++)
printf("\n[%d]\t%s\t%s\t%.2f",i+1,a[i].name,a[i].acn,a[i].bal);
}
void main()
{
printf("Enter the number of customers: ");
scanf("%d",&n);
printf("Enter the details of %d customers:\n",n);
for(i=0;i<n;i++)
{
printf("\nCustomer-%d",i+1);
printf("\nFirst Name: ");
fflush(stdin);
gets(a[i].name);
printf("Account Number: ");
fflush(stdin);
gets(a[i].acn);
printf("Account Balance: ");
scanf("%f",&a[i].bal);
}
for(i=0;i<n;i++)//The problem seems to be in this loop
while(strlen(a[i].name)<10)
strcat(a[i].name," ");
add();
}
输入:
Enter the number of customers: 2
Enter the details of 2 customers:
Customer-1
First Name: Aarav
Account Number: ASDF1234
Account Balance: 1200
Customer-2
First Name: Asd
Account Number: abcd1122
Account Balance: 999.9
输出:
S.No. Name Acc. No. Balance(in Rs.)
[1] Aarav 1300.00
[2] Asd 999.90
解决方案
您的程序中几乎没有需要纠正的地方。
使用
fgets
而不是gets
因为gets
没有边界检查并且存在读取超出分配大小的危险。使用的时候
fgets
,scanf
甚至gets
都是\n
从标准缓冲区中读取剩下的字符,所以使用fgets
得当可以避免使用。(scanf
也避免使用空格字符但不能用于读取多字串)删除
fflush(stdin)
,它不是必需的,您可以在此处查看原因最后,但肯定不是最不重要的使用,
int main()
而不是void main()
推荐阅读
- python - 已解决:如何删除密钥重复错误 Django?
- javascript - 来自 url、web、cloud 的自定义 R 闪亮文件输入
- javascript - 用消息中的值替换占位符 - Javascript
- jenkins - 如果部署后运行状况检查失败,则回滚到上次工作的产品部署
- oci-python-sdk - IdentityClient.get_user() 在隔间 ID 字段中返回租户 OCID
- node.js - 如何在中间件中使用来自 firebase db 的数据来验证用户身份
- php - 本地环境中的 Xdebug 错误 [加载 /usr/local/lib/php/pecl/20190902/xdebug.so 失败:]
- android - 动态功能模块中的 androidTest espresso 测试用例无法构建/运行 - 任务“:dfm:mergeLibDexDebugAndroidTest”执行失败
- node.js - 如何确保仅在完成 Stripe 付款后才调用路由?
- google-cloud-datastore - Cloud Datastore 事务在未定义显式回滚的情况下终止