Как выполнить вторую функцию в C? - PullRequest
0 голосов
/ 06 мая 2020

Всякий раз, когда я ввожу выбор 2 , он не выполняет функцию view_list () . Вместо этого он запускает его с первой функции new_a cc () . Также else не работает. Как решить эту проблему?

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

int new_acc();
int view_list();

int main(){

    int one=1, two=2;
    int new_account, list;

    printf("%d. Create new account\n",one);
    printf("%d. View customers list\n",two);

    printf("Enter you choice: ");
    if (scanf("%d",&one)){new_account = new_acc();}  // calling a function 
    else if (scanf("%d",&two)){list = view_list();} // calling a function 
    else {printf("Sorry this is not the correct option"); break;}
    return 0;
}

int new_acc(){
    char name;
    printf("Enter your name: ");
    scanf("%s",&name);

    return 0;
}

int view_list(){
    printf("view list");
    return 0;
}

Ответы [ 2 ]

0 голосов
/ 06 мая 2020

Возвращаемое значение scanf () - это количество возвращаемых значений, а не собственное фактическое значение. Код должен быть:

int value = 0;
scanf("%d",&value);
if(value == one){new_account = new_acc();}
else if (value == two){list = view_list();}
else {printf("Sorry this is not the correct option"); break;}

Другие рекомендации:

  1. Последний break ничего не делает;
  2. Сделайте отступ в своем коде. намного легче читать:

    int value =0;
    scanf("%d",&value);
    if(value == one)
    {
       new_account = new_acc();
    }
    else if (value == two)
    {
       list = view_list();
    }
    else 
    {
       printf("Sorry this is not the correct option");
    }
    
0 голосов
/ 06 мая 2020

Возвращаемое значение scanf() - это количество прочитанных данных.

printf("Enter you choice: ");
if (scanf("%d",&one)){new_account = new_acc();}  // calling a function 
else if (scanf("%d",&two)){list = view_list();} // calling a function 
else {printf("Sorry this is not the correct option"); break;}

должно выглядеть как

printf("Enter you choice: ");
if (scanf("%d",&one)) != 1) { puts("input read error"); return 1; }
if (one == 1){new_account = new_acc();}  // calling a function 
else if (one == 2){list = view_list();} // calling a function 
else {printf("Sorry this is not the correct option"); return 1;}

или

printf("Enter you choice: ");
if (scanf("%d",&one)) != 1) { puts("input read error"); return 1; }
switch (one) {
    case 1: new_account = new_acc(); break;  // calling a function 
    case 2: list = view_list(); break; // calling a function 
    default: printf("Sorry this is not the correct option"); break;
}

Кстати , выполнение вашего new_acc() опасно. Спецификатор %s принимает строку положительной длины, в то время как в вашем буфере есть место только для одного символа. Даже ввод односимвольной строки вызовет переполнение буфера, так как завершится нулевой символ. Должно получиться

int new_acc(){
    char name[1024]; /* allocate an array */
    printf("Enter your name: ");
    scanf("%1023s",name); /* specify length limit (buffer size - 1 (terminating null character)) to avoid buffer overrun */

    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...