2014-03-14 17 views
1

空洞本身工作正常,但我如何回憶從一個空隙到另一個空隙的變量? 遇到的問題IM是在enter_user_name(void)名字沒有被放入的printf在enter_user_exam(void)如何在void函數中使用scanf並將結果在主函數中出現以用於C中的另一個void?

#include <stdio.h> 
#include <ctype.h> 
#include <string.h> 

void enter_user_name(void); 
void enter_user_exam(void); 

int main() 
{ 

    enter_user_name(); 
    enter_user_exam(); 
    return 0; 
} 

// Define the function: 
// Note: No semicolon after function name 
void enter_user_name() 
{ 
    /* Need next two lines for printf() operation */ 
    setvbuf(stdout, 0, _IONBF, 0); 
    setvbuf(stdin, 0, _IONBF, 0); 

    char guyname[32]= {0}; 
    char lastname[32]= {0}; 
    printf("Enter your first and last name : "); 
    scanf("%s %s", &guyname, &lastname); 

    guyname[0] = toupper(guyname[0]); 
    int len = strlen(guyname); 
    for(int i=1; i<len ; i++) 
    { 
     guyname[i] = tolower(guyname[i]); 
    } 

    lastname[0] = toupper(lastname[0]); 
    int len1 = strlen(lastname); 
    for(int k=1; k<len1; k++) 
    { 
     lastname[k]= tolower(lastname[k]); 
    } 

    printf("Your name is %s %s\n", guyname, lastname); 

} 

void enter_user_exam(void) 
{ 
    /* Need next two lines for printf() operation */ 
    setvbuf(stdout, 0, _IONBF, 0); 
    setvbuf(stdin, 0, _IONBF, 0); 

    int option = 0; 
    int sum = 0; 
    char guyname[32]= {0}; 
    char lastname[32]= {0}; 
    int maxscore = 100; 
    int scores[3] = {0}; 
    float average = ((float)sum/(maxscore*3)) * 100; 

    for(int i=0; i<3; i++) 
    { 
     printf("Assuming the max score is 100, what was your score for exam %i?\n",i+1); 
     scanf("%i",&scores [i]); 
     while(scores [i]>maxscore) 
     { 

      printf("Your score should not be higher than max score.\n"); 
      printf("What was your score for exam %i?\n",i+1); 
      scanf("%i",&scores [i]); 

     } 

    } 
    for(int i=0; i<3; i++) 
    { 
     sum += scores[i]; 
    } 
    average = ((float)sum/(maxscore*3)) * 100; 
    printf("%s %s, the exam scores you input are %i ,%i ,and %i\n\n",guyname,lastname, scores[0], scores[1], scores[2]); 
} 
+0

你不需要做'stdout'(或'stdin')無緩衝。需要時只需'fflush''stdout'。 –

+0

'的scanf( 「%S%S」,&guyname,&姓氏);'無需放置'&'以%s預計'字符*'F上的陣列就足夠了的意思只是基地址。 –

回答

2

有三種方法從一個函數找回數據:

  1. 該函數返回數據
  2. 功能獲得一個指向數據作爲參數,並填充它
  3. 數據存儲在全局變量

在我看來,上述列表中的優先順序。最好的解決方案通常是返回數據(儘管你必須小心不要返回指向局部變量的指針),而最糟糕的是它有全局變量。

相關問題