我制作了一个程序,以多个输入作为字符串,存储和打印它们。不知何故,存储在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发布于 2020-12-20 07:43:47
scanf() 那么 gets() 是坏
scanf("%d",&n);读取整数,但在stdin中留下以下'\n',gets()将其作为空字符串""读取。
我建议使用fgets()将所有行读入一个相当大的缓冲区,然后使用sscanf()、strtol()等进行解析。
代码过度填充缓冲区
a[i].nam只有足够的空间容纳9个字符,然后是空字符。添加一个空格,直到它有更长的长度,这9个超填充.name[10]。
struct Bank {
char name[10],acn[8];
float bal;
} a[100];
while(strlen(a[i].name)<10)
strcat(a[i].name," ");使用while(strlen(a[i].name)<9)来填充空格,但不要太多。
钱需要特殊的considerations。现在,考虑最低教派(美分)的long。在double中读取,然后读取long balance = lround(input*100.0);
还有其他弱点。
发布于 2020-12-20 07:24:54
在你的程序中几乎没有什么东西需要修正。
fgets而不是gets,因为在gets中没有边界检查,并且存在读取超出分配大小的危险。fgets、scanf甚至gets时,都会从标准缓冲区读取\n字符,所以使用fgets时,如果使用得当,就可以避免(scanf也避免空格字符,但不能用于读取多字字符串)<代码>G 216
fflush(stdin),它不是必需的,您可以看到原因void main()和
int main()来代替int main()发布于 2020-12-20 07:28:20
你有这个:
struct Bank
{
char name[10],acn[8];
float bal;
}a[100];因为C字符串必须以NUL字符(又名'\0')结尾,所以name最多可以有9个字符长。
但在这里
while(strlen(a[i].name)<10)
strcat(a[i].name," ");你一直在添加空格直到它有10个字符长。换句话说,你在数组之外写东西。
将name更改为name[11]
此外,还应避免gets和fflush(stdin)。
https://stackoverflow.com/questions/65377718
复制相似问题