gpt4 book ai didi

c - 存储字符串的某些部分

转载 作者:行者123 更新时间:2023-11-30 15:58:16 26 4
gpt4 key购买 nike

对于下面的代码,我的输入如下:

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].nameintreadin[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;
}

关于c - 存储字符串的某些部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9881922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com