C ++将文件行分隔为字符串和整数

问题描述 投票:0回答:1

在我的课程中,我被分配一个程序,该程序将允许用户输入他们的姓名和分数,如果输入的分数大于文件中存储的十个分数之一,则该分数(及其名称)将被新的分数和名称覆盖。但是,我不知道如何将名称和分数与文件分开(因为它们在同一行),以便可以通过条件语句运行int。

这是我的分数文件的外观:

Henry | 100
Thomas | 85
Barry | 79
James | 76
Connor | 74
Jake | 70
Sam | 66
Rory | 60
Joe | 52
Darren | 49

假设用户输入分数为75的名称,程序应从列表中删除Darren(分数最低的玩家),并添加新名称和分数,根据我的分配,分数不必是按顺序排列的简要。

这是到目前为止我得到的代码:

void enterScore()
{
    std::cout << "Please enter your name" << std::endl;
    std::string name;
    std::cin >> name;

    std::cout << "Please enter your score" << std::endl;
    int score;
    std::cin >> score;

    std::string fileNames[10];  //Array for storing all 10 of the names already in the file
    int fileScores[10];  //Array for storing all 10 of the scores already in the file

    std::fstream inoutFile("Scores.txt");

    if (inoutFile.is_open())
    {
        //Divide the names and scores
        //E.G:
        //fileName[0] = Henry    fileScore[0] = 100
        //fileName[1] = Thomas   fileScore[1] = 85

        //Loop through all array cells
        //if fileName[i] < score, then:             Assignment brief states that the scores do not need to be sorted
        inoutFile << name << " | " << score << std::endl;  //Overwrite lowest score
    }
    else
    {
        std::cout << "File could not be opened" << std::endl;
    }
}
c++ text-files
1个回答
0
投票

我已将伪代码添加到您的代码示例中,希望在没有给出完整家庭作业解决方案的情况下指导您正确的方向。

void enterScore()
{
    std::cout << "Please enter your name" << std::endl;
    std::string name;
    std::cin >> name;

    std::cout << "Please enter your score" << std::endl;
    int score;
    std::cin >> score;

    std::string fileNames[10];  //Array for storing all 10 of the names already in the file
    int fileScores[10];  //Array for storing all 10 of the scores already in the file

    std::fstream inoutFile("Scores.txt");

    if (inoutFile.is_open())
    {
        //Loop on each line of the file, line by line
        // split the string into two parts, one before the pipe ( | ) and the other part after the pipe. There are multiple ways to do this, one would be to loop on each character of the string value and use a condition.

        //increment a counter variable

        //fileNames[myCounter] = assign first part of the string obtained above.
        //fileScores[myCounter] = assign second part of the string obtained above.


    // Rest of logic depends on precise requirement, see below
    }
    else
    {
    std::cout << "File could not be opened" << std::endl;
    }
}

如果您只想覆盖最低的分数,则需要完全循环文件以找到要替换的最佳行。但是,如果要替换任何较低的分数,则可以只执行一次循环。当您阅读文件中的行时,只要找到得分较低的行,就可以替换它。

话虽这么说,为使操作简单起见,我建议阅读整个文件,并使用一个变量来保持最小值及其在数组中的位置。

[一旦有了这个,为简单起见,我建议编写第二个循环,在该循环中,用新数组替换了所需的值,然后使用两个数组中的值逐行写入文件。

您可以在Google上搜索我的大多数注释/伪代码来获取所需的代码。

© www.soinside.com 2019 - 2024. All rights reserved.