首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >保存到文件中的字符串数组

保存到文件中的字符串数组
EN

Stack Overflow用户
提问于 2011-12-10 20:44:32
回答 3查看 190关注 0票数 0

基本上,我想从文件中读取高分,并检查用户是否在记分板上获得了足够的分数。我试着这样做:

代码语言:javascript
复制
string initials[10];
int scores[10];

//load txt
ifstream highscores("highscores.txt");
if(highscores.is_open())
{
   while(highscores.good())
   {
    for(int x=0;x<10;x++)
    {
        getline(highscores,initials[x],' '); 
        highscores >> scores[x];
    }
   }

    }

首字母的长度只有3个字符,所以我可以实现一个2dim。数组,但我想用字符串来尝试它。它显示我生成了一个大小为10的字符串,我该如何编写它才能使用10个数组而不是1个数组?(我知道我可以从array1中将它们命名为10个数组。到10,循环遍历它们听起来要好得多。高分文件只是一组10个缩写的AAA,BBB等和一些分数。

Highscores.txt示例:

代码语言:javascript
复制
AAA 5000
BBB 4000
CCC 3000
EN

Stack Overflow用户

回答已采纳

发布于 2011-12-10 21:00:23

使用std::map保存首字母和相关分数。例如:

代码语言:javascript
复制
int main()
{
    // Map is keyed by initials.
    std::map<std::string, int> scores;

    std::ifstream in("highscores.txt");
    if (in.is_open())
    {
        for (;;)
        {
            std::string line;
            std::getline(in, line);

            if (!in.good())
            {
                break;
            }

            const size_t space_idx = line.find(' ');
            if (std::string::npos != space_idx)
            {
                // The initials are everthing before the space.
                // Score everything after the space.
                scores[line.substr(0, space_idx)] =
                    atoi(line.substr(space_idx + 1).c_str());
            }
        }
        in.close();
    }

    // Check who has achieved required score.
    for (std::map<std::string, int>::iterator i = scores.begin();
         i != scores.end();
         i++)
    {
        if (i->second > 3500)
        {
            std::cout << i->first << "\n";
        }
    }
    return 0;
}
票数 1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8456581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档