簡體   English   中英

C 程序不在結構中打印字符串

[英]C Program not printing the string in a structure

我制作了一個程序來將多個輸入作為字符串,存儲和打印它們。 不知何故,存儲在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

Output:

S.No.   Name            Acc. No.        Balance(in Rs.)
[1]     Aarav                   1300.00
[2]     Asd                     999.90

您的程序中幾乎沒有需要糾正的地方。

  1. 使用fgets而不是gets ,因為在gets中沒有邊界檢查並且存在讀取超出分配大小的危險。

  2. 使用fgets getsscanf甚至 get 它們都從標准緩沖區中讀取剩余的\n字符,因此使用fgets如果我們正確使用它,我們可以避免它。( scanf也避免了空格字符,但它不能用於讀取多字字符串)

  3. 刪除fflush(stdin) ,不需要你可以在這里看到原因

  4. 最后,但同樣重要的是使用int main()而不是void main()

你有這個:

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]

除此之外,應該避免getsfflush(stdin)

scanf()然后gets()不好

scanf("%d",&n); 讀取 integer,但在stdin中留下以下'\n'gets()讀取為空字符串""

我建議使用fgets()將所有行讀入一個相當大的緩沖區,然后使用sscanf()strtol()等進行解析。


代碼溢出緩沖區

a[i].nam只有足夠的空間容納 9 個字符,然后是null 字符 附加一個空格,直到它的長度超過 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)填充空格,但不要太多。


金錢需要特別考慮 現在,考慮做long最低面額(美分)。 讀入double然后long balance = lround(input*100.0);

存在其他弱點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM