Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

O programa não compila corretamente a parte CADASTRAR CONTAS(peço ajuda para corrigí-lo)

0 votes
asked May 6, 2021 by paulo magalhaes (1,480 points)
Faça um programa que realize o cadastro de contas bancárias com as seguintes informações: número da conta, nome do cliente e saldo. O banco permitirá o cadastramento de apenas quinze contas e não poderá haver mais de uma conta com o mesmo número. Crie o menu de opções a seguir:

1 Cadastrar contas.

2 Visualizar todas as contas de determinado cliente.

3 Excluir a conta com menor saldo (Suponha a não existência de saldos iguais).

4 Sair.

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define tam 15

main(){

       struct banco{

              int num_conta;

              char cliente[50];

              float saldo;

       };

       struct banco contas[15];

       int i,j,menu,ver_conta,contcliente=0,cont=0,numero;

       char vnome[50];

       while (menu!=4){

              printf("\t\t* * * * * * * * * * * * * * * * * *\n");

              printf("\t\t*      CONTAS BANCARIAS       *\n");

              printf("\t\t* * * * * * * * * * * * * * * * * *\n");

              printf("\t\t*       Menu de opções            *\n");

              printf("\t\t* * * * * * * * * * * * * * * * * *\n");

              printf("\t\t* [1] Cadastrar as Contas         *\n");

              printf("\t\t* [2] Visualizar todas as contas  *\n");

              printf("\t\t* [3] Visualizar conta            *\n");

              printf("\t\t* [4] Sair                        *\n");

              printf("\t\t* * * * * * * * * * * * * * * * * *\n");     menu=0;

           printf("\n\n\t\t MENU: ");

               scanf("\t\t%d",&menu);

               switch (menu){

                       case 1:

                              printf("\n\n");

                              do{

                                       printf("\t Digite o Numero da Conta: ");

                                       scanf("\t%d",&ver_conta);

                                       for (i=0;i<tam;i++){

                                            if (ver_conta!=contas[i].num_conta){

                                                contcliente++;

                                            }           }

                                            if (contcliente==15){

                                                contas[cont].num_conta=ver_conta;

                                                printf("\t Digite o Nome do Cliente:");

                                                scanf("\t%s",&contas[cont].cliente);

                                                printf("\t Digite o saldo:");

                                                scanf("\t%f",&contas[cont].saldo);

                                                printf("\n");

                                                contcliente=0;

                                             }

                                             else{

                                                   cont=cont-1;

                                                   printf("Conta existe \n");

                                                   contcliente=0;

                                                }

                                                cont++;

                                        }while(cont<15);

                                        break;

                        case 2:

                               printf("\n\n");

                               printf("\tDigite o nome do cliente:");

                               scanf("\t%s",&vnome);

                               for (i=0;i<tam;i++){

                                     numero=(strcmp(vnome,contas[i].cliente));

                                     if (numero==0)

                                         printf("\n  \n  \tNumero  Conta:  %d  -  Nome:  %s  -  Saldo: %f\n",contas[i].num_conta,contas[i].cliente,contas[i].saldo);

                               }

                               break;

                        case 3:

                               printf("\n\n");

                               printf("\t Digite o Numero da Conta:");

                               scanf("\t%d",&ver_conta);

                               for (i=0;i<tam;i++){

                                    if (ver_conta==contas[i].num_conta){

                                        printf("\n  \n  \tNumero  Conta:  %d  -  Nome:  %s  -  Saldo: %f\n",contas[i].num_conta,contas[i].cliente,contas[i].saldo);

                                    }

                               }

                                break;

                        case 4:

                               break;

                        default:

                               printf("OPCAO INVALIDA");

                                                   }

                }

                getch();

      }

2 Answers

0 votes
answered May 10, 2021 by Peter Minarik (86,130 points)
edited May 11, 2021 by Peter Minarik

Your Code

The code compiles! And runs. :)

I didn't have time to do a thorough testing.

However just by looking at it, I see problems.

Let's go line by line and see these issues.

  1. contas does not use tam to set the size, so if tam is changed, contas will have the wrong size.
  2. The structure banco is defined within the main method. While this works, you could also define it in the whole program and use the structure elsewhere (e.g. other functions could use it).
  3. The variable j is not used.
  4. menu is not initialized (it has a random value) and you read its value in the while loop. Hence there is a possibility you never enter the while loop in the first place.
  5. menu = 0; is in the same line as a printf. It is highly advised to keep one instruction at a line. It makes the code more readable.
    Also, this is pointless as two lines below menu is assigned a value via scanf.
  6. The title line "*      CONTAS BANCARIAS       *" is not as wide as its surrounding lines.
  7. scanf regularly has one or more '\t' in the format string. It is not needed.
  8. scanf("%s")doesn't allow reading of strings with whitespace in it (practically [FirstName][SPACE][LAST NAME] is not possible). See how you could do this in my solution below.
  9. if (ver_conta != contas[i].num_conta) is in a for loop from 0 to tam and it compares ver_conta against memory garbage, unless all  the accounts are initialized. You should only go in your for loop until you read the number of accounts existing in the system.
  10. contcliente is set to 0 in both the then and else branches. You can just set it to 0 outside of the if.
  11. cont is not compared to tam.
  12. I do not think you're supposed to register all the possible number of accounts in one go. You probably should do only one account at a time. Do the next when the user chooses the same option again.
  13. numero = strcmp(vnome, contas[i].cliente); would read memory garbage when not all the accounts are created.
  14. if (ver_conta == contas[i].num_conta) would read memory garbage when not all the accounts are created.
  15. This is the English translation (via Google Translate):
    "3 Delete the account with the lowest balance (Suppose there are no equal balances)."
    I do not see any account deletion where the balance is 0 for option 3.
    Your code doesn't seem to do what was in the instruction.
  16. getch() does not exist. It's getchar().
  17. When you read into a char array, you do not need to get the memory address. The character array (variable) is already a memory address. This is not a problem, the compiler is smart enough to know what you wanted to do, yet it issues a warning for it.
  18. Not a terrible problem, but you could use functions for shared functionality (e.g. printing out account details) instead of copy-pasting code around.
  19. One more useful tip: it's often advised to sort your included libraries by name. It's particularly useful when you want to avoid including something multiple times (you'd find duplicates below each other.)

To be continued in a different post ...

0 votes
answered May 11, 2021 by Peter Minarik (86,130 points)
edited May 11, 2021 by Peter Minarik

... continued from my other post.

My Solution

Here's my take on the problem. I didn't care to validate if numbers are provided when asked for, but I made sure the user can enter names with spaces. See GetLine();

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_CLINET_NAME   10 /* Including the terminating zero */
#define MAX_ACCOUNT_COUNT 2
#define UNUSED_ACCOUNT    0xFFFFFFFF
#define MAX_USER_INPUT    255

typedef struct
{
    unsigned int accountNumber;
    char clientName[MAX_CLINET_NAME];
    float balance;
} Account;

static Account accounts[MAX_ACCOUNT_COUNT];

static char * lineBuffer = NULL;    // Used by GetLine. Do not modify.
static size_t lineBufferLength = 0; // Used by GetLine. Do not modify.

static char * GetLine(size_t max)
{
    ssize_t charsRead = getline(&lineBuffer, &lineBufferLength, stdin);
    if (charsRead == -1)
    {
        printf("Error happend. Program terminated.\n");
        exit(1);
    }

    if (charsRead < max)
        lineBuffer[charsRead - 1] = '\0';   // Do not include the new line character
    else
        lineBuffer[max - 1] = '\0';         // Do not allow more characters than max
    
    return lineBuffer;
}

static void GetLineInto(char * buffer, size_t max)
{
    strcpy(buffer, GetLine(max));
}

static Account * FindNextUnusedAccount()
{
    for (int i = 0; i < MAX_ACCOUNT_COUNT; i++)
        if (accounts[i].accountNumber == UNUSED_ACCOUNT)
            return &accounts[i];

    return NULL;
}

static void PrintAccount(const Account * account)
{
    printf("Account number: %u\n", account->accountNumber);
    printf("Client Name: %s\n", account->clientName);
    printf("Balance: $%.2f\n", account->balance);
}

static bool IsAccountNumberInUse(unsigned int accountNumber)
{
    for (int i = 0; i < MAX_ACCOUNT_COUNT; i++)
    {
        if (accounts[i].accountNumber == accountNumber)
            return true;
    }
    
    return false;
}

static void SetupAccount(Account * account)
{
    unsigned int accountNumber;
    printf("Account number: ");
    scanf("%u", &accountNumber);
    if (IsAccountNumberInUse(accountNumber))
    {
        printf("This account is already in use. Duplicate accounts are not allowed.\n");
        return;
    }
    if (accountNumber == UNUSED_ACCOUNT)
    {
        printf("This account number is reserved for internal use.\n");
        return;
    }
    account->accountNumber = accountNumber;
    
    printf("Client Name: ");
    getchar(); // Clearning the \n from the stdin. This is one left by scanf.
    GetLineInto(account->clientName, MAX_CLINET_NAME);

    printf("Balance ($): ");
    scanf("%f", &account->balance);
}

static void CreateNewAccount()
{
    printf("NEW ACCOUNT\n");
    printf("-----------\n");
    Account * nextUnusedAccount = FindNextUnusedAccount();
    if (!nextUnusedAccount)
    {
        printf("I'm sorry, but we ran out of accounts for the bank.\nPlease come back at a later time.\n");
        return;
    }
    
    SetupAccount(nextUnusedAccount);
}

static void ShowSpecificAccounts()
{
    printf("SHOW ACCOUNTS\n");
    printf("-------------\n");
    printf("Please, enter the name of the account holder: ");
    getchar(); // Clearning the \n from the stdin. This is one left by scanf.
    char * name = GetLine(MAX_CLINET_NAME);
    printf("\nAccounts found:\n");
    printf("~~~~~~~~~~~~~~~\n");
    bool accountFound = false;
    for (int i = 0; i < MAX_ACCOUNT_COUNT; i++)
    {
        if (accounts[i].accountNumber != UNUSED_ACCOUNT &&
            strcmp(accounts[i].clientName, name) == 0)
        {
            PrintAccount(&accounts[i]);
            printf("\n");
            if (!accountFound)
                accountFound = true;
        }
    }
    if (!accountFound)
        printf("No account found for client '%s'.\n", name);
}

static void DeleteAccountWithLowestBalance()
{
    printf("DELETE ACCOUNT WITH LOWEST BALANCE\n");
    printf("----------------------------------\n");
    Account * accountWithLowestBalance = NULL;
    for (int i = 0; i < MAX_ACCOUNT_COUNT; i++)
    {
        if (accounts[i].accountNumber != UNUSED_ACCOUNT &&
            (accountWithLowestBalance == NULL ||
            accounts[i].balance < accountWithLowestBalance->balance))
        {
            accountWithLowestBalance = &accounts[i];
        }
    }
    
    if (accountWithLowestBalance)
    {
        printf("Account deleted:\n");
        printf("~~~~~~~~~~~~~~~~\n");
        PrintAccount(accountWithLowestBalance);
        accountWithLowestBalance->accountNumber = UNUSED_ACCOUNT;
    }
    else
    {
        printf("There isn't any account in the system.\n");
    }
}

int main()
{
    for (int i = 0; i < MAX_ACCOUNT_COUNT; i++)
        accounts[i].accountNumber = UNUSED_ACCOUNT;

    int choice;
    do
    {
        printf("FIRST BANK - ACCOUNT MANAGEMENT\n");
        printf("===============================\n");
        printf("1. Create account\n");
        printf("2. Show accounts for customer\n");
        printf("3. Delete account with lowest balance\n");
        printf("4. Exit\n");
        do
        {
            printf("? ");
            scanf("%d", &choice);
        } while (choice < 1 || choice > 4);
        
        printf("\n");
        switch (choice)
        {
            case 1: CreateNewAccount(); break;
            case 2: ShowSpecificAccounts(); break;
            case 3: DeleteAccountWithLowestBalance(); break;
            case 4: break;
        }
        printf("\n");
    } while (choice != 4);
    
    if (lineBuffer)
        free(lineBuffer);

    printf("Good bye!\n");

    return 0;
}
commented May 15, 2021 by paulo magalhaes (1,480 points)
Peço ajuda pra faze-lo em python.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...