簡體   English   中英

如何執行C中的第二個function?

[英]How to execute the second function in C?

每當我輸入選擇2時,它都不會執行view_list() function。 相反,它從第一個 function 開始,即new_acc() 其他的也不起作用。 如何解決這個問題呢?

#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;
}

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說明符將接受正長度字符串,而您的緩沖區只有一個字符的空間。 即使輸入一個字符的字符串也會導致緩沖區溢出,因為會有終止 null 字符。 它應該像

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;
}

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"); }

暫無
暫無

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

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