[英]Storing certain parts of a string
對於以下代碼,我的輸入如下:
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;
}
if
語句后的字符串s
是“ nameint” ...我想將名稱存儲為readin[i].name
,將int
為readin[i].score
...我該怎么做?
編輯
這有效:
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;
}
假設您想為此使用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++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.