2012-03-27 144 views
0

對於下面的代碼的某些部分,我輸入的是如下:存儲字符串

score Bob 10 
score Jill 20 
score Han 20 
highscore 
best Bob 

代碼:

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


typedef struct score_entry 
{ 
    char name[21]; 
    int score; 
} score_entry; 


int main(void) { 
    int i; 
    char s[100]; 
    score_entry readin[30]; 

    while (1 == scanf("%s",(char*)s)) 
    { 
     if (strncmp(s,"score",5)){ 
      //how to store string an name ? 
      i++; 
     } 
    } 
    return 0; 
} 

字符串sif後聲明是 「nameint」 ...我想將名稱存儲到readin[i].nameintreadin[i].score ...我該如何做到這一點?

回答

1

編輯

這工作:

typedef struct score_entry 
{ 
    char name[21]; 
    int score; 
} score_entry; 

int main() 
{ 

    int i, j; 
    int input_tokens; 
    int score; 
    int highest_score; 
    int highest_individual_score; 
    char input[100]; 
    char name[21]; 
    char scoretoken[10]; 
    score_entry readin[30] = {{0}}; 

    i = 0; 

    while(i < 30 && fgets(input, 100, stdin) != NULL) 
    { 
     input_tokens = sscanf(input, "%9s %20s %d", scoretoken, name, &score); 
     if (input_tokens == 3) 
     { 
      if (strncmp(scoretoken, "score", 5) == 0) 
      { 
       strncpy(readin[i].name, name, 20); 
       readin[i].score = score; 
       i++; 
      } 
     } 
     else if (input_tokens == 2) 
     { 
      if (strncmp(scoretoken, "best", 4) == 0) 
      { 
       highest_individual_score = 0; 
       for (j = 0; j < 30; j++) 
       { 
        if (strncmp(readin[j].name, name, 20) == 0 && readin[j].score > highest_individual_score) 
        { 
         highest_individual_score = readin[j].score; 
        } 
       } 
       printf("Highest score for %s: %d\n", name, highest_individual_score); 
      } 
     } 
     else if (input_tokens == 1) 
     { 
      if (strncmp(scoretoken, "highscore", 9) == 0) 
      { 
       highest_score = 0; 
       for (j = 0; j < 30; j++) 
       { 
        if (readin[j].score > highest_score) 
        { 
         highest_score = readin[j].score; 
        } 
       } 
       printf("Highest score: %d\n", highest_score); 
      } 
     } 
    } 

    return 0; 
} 
+0

對不起,我更新了這個問題,有時我會輸入高分和最好的「randomname」.....最好的高分和得分都是命令....所以我不會總是輸入3個東西......這就是爲什麼我想避免3件事情的scanf ......對不起。 – Thatdude1 2012-03-27 01:28:27

+0

@Beginnernato你將如何處理'highscore'和'best [somename]'的輸入? – 2012-03-27 01:31:21

+0

@Beginnernato我編輯了代碼以允許不同的輸入。 – 2012-03-27 01:35:06

0

假設你想用scanf函數對於這一點,那麼你可能想:

int i, num; 
char szScore[10]; 
i=0; 
while(scanf("%s, %s,%d", szScore, s, &num)) 
{ 
    if(!strncmp(szScore, "score", 5) 
    { 
    strcpy(readin[i].name, s); 
    readin[i].score = num; 
    i++; 
    } 
} 
+0

怎麼樣的詞 「分數」,我不想存儲? – Thatdude1 2012-03-27 01:07:58

+0

IDK,單詞score?我的回答是基於您可能難以理解點(。)或( - >)訪問器的假設。你想要做什麼? – Eric 2012-03-27 01:11:15

+0

基本上,單詞得分後面跟着一個名字(字符串)和一個分數(int)...我輸入了分數,因爲它基本上告訴我要記錄這個人的名字,它是數組中的分數......單詞「分數」本身沒有其他含義,所以我不想存儲它。 – Thatdude1 2012-03-27 01:15:18