对于下面的代码,我的输入如下:
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;
}
s
语句后面的字符串if
是“nameint”...我想将名称存储到readin[i].name
,将int
存储到readin[i].score
......我怎么能这样做?
答案 0 :(得分: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;
}
答案 1 :(得分: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++;
}
}