2012-03-27 111 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