【问题标题】:Splitting lines from an external text file in to a structure?将外部文本文件中的行拆分为结构?
【发布时间】:2014-06-28 00:56:16
【问题描述】:

我真的不知道如何解释这个问题。但在这里... 假设我有一个外部文本文件,它的内容是这样的:

1 Crysis 2012 Crytek Ubisoft
2 FarCry 2009 Crytek Ubisoft
3 Need_For_Speed 1695 EA Ubisoft
4 Assassin'sCreed 2008 Ubisoft Ubisoft
5 COD 2010 Activision Ubisoft

然后我使用了这个代码:

if (fout.is_open())
{
    std::string delim = " ";
    size_t pos = 0;
    std::string token;

    while (getline(fout, line))
    {
        while ((pos = line.find(delim)) != std::string::npos) 
        {
            token = line.substr(0, pos);
            std::cout << token << std::endl;
            line.erase(0, pos + delim.length());
        }
        std::cout << line << std::endl;
    }
}

此代码拆分文本行并输出以下内容

1
Crysis
2012
Crytek
Ubisoft
2
FarCry
2009
Crytek
Ubisoft
3
Need_For_Speed
1695
EA
Ubisoft
4
Assassins'sCreed
2008
Ubisoft
Ubisoft
5
COD
2010
Activision
Ubisoft

我真正想要的是在每个循环中创建一个新结构并创建它的 5 个变量来保存每个单独游戏的每个属性。例如

struct Game
{
int id;
string title;
int year;
string developer;
string publisher;
};

现在从输出:

1
Crysis
2012
Crytek
Ubisoft

当循环运行时,我想创建一个新的“游戏”结构并将这些值分配给它的变量,然后将结构推入向量中。

以下是我正在尝试创建的内容以及我已经走了多远的摘要:

该程序是一个游戏数据库。用户可以添加、删除、搜索和编辑数据库中的任何项目。随着程序运行和用户添加游戏,它成功写入外部 .txt 文件并被推送到向量的末尾。现在一切都好。但是当我关闭程序并再次运行时,文本文件中有数据但向量为空。所以我希望用 .txt 文件中的数据再次填充向量,以便用户可以继续使用数据库。

我不知道我是否充分解释了这个问题。或者我可能已经过度解释了。我实际上是 C++ 的菜鸟。

提前谢谢..


这是我正在开发的程序的完整代码...


#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;


struct  Game

{
    int id;
    int year;
    string title;
    string publisher;
    string developer;
};

void ShowData(vector<Game> myDatabase)
{
        cout << endl;
        for(size_t i = 0; i <= myDatabase.size()-1; i++)
        {
            cout << endl;
            cout << "-------------------------------------------------------"<<endl;
            cout << "                ITEM NO" << " " << i + 1 << " " <<endl;
            cout << "-------------------------------------------------------"<<endl;
            cout << "    TITLE: " << myDatabase[i].title << endl;
            cout << "     YEAR: " << myDatabase[i].year << endl;
            cout << "DEVELOPER: " << myDatabase[i].developer << endl;
            cout << "PUBLISHER: " << myDatabase[i].publisher << endl;

        }

}

int _tmain(int argc, _TCHAR* argv[])
{
    string option;
    int serialNumber = 0;
    int count = 0;
    string line;


    vector<Game> Database;

    fstream fout;
    fout.open("Database.txt");
    if (fout.is_open())
    {
        std::string delim = " ";
        size_t pos = 0;
        std::string token;
        while (getline(fout, line))
        {

            Game newGame;
            std::cout << line << std::endl;
        }

        while (getline(fout, line))
        {

            while ((pos = line.find(delim)) != std::string::npos) 
            {

                token = line.substr(0, pos);
                std::cout << token << std::endl;
                line.erase(0, pos + delim.length());
            }
            std::cout << line << std::endl;
        }
    }
    else
    {
        cout << "There was an error opening the file.";
    }

    cout << endl;
repeat: 
    cout << endl;

    cout << "ADD | SHOW | DELETE | EDIT | SEARCH " << endl;

    cout << "SAY :  ";
    cin >> option;

    if(option == "ADD" || option == "Add" || option == "add")
    {
        serialNumber += 1;
        Game NewGame;
        NewGame.id = serialNumber;
        cout << endl << "Name: ";
        cin >> NewGame.title;
        cout << "Year: ";
        cin >> NewGame.year;
        cout << "Developer: ";
        cin >> NewGame.developer;
        cout << "Publisher: ";
        cin >> NewGame.publisher;
        cout << endl;

        Database.push_back(NewGame);
        cout << endl;
        cout << "Size is: " << Database.size();


        fout <<  serialNumber << " " << Database[Database.size() - 1].title << " " << Database[Database.size() - 1].year << " "<< Database[Database.size() - 1].developer << " " << Database[Database.size() - 1].publisher << endl;


        goto repeat;

    }
    if (option == "SHOW" || option == "Show" || option == "show")
    {
        ShowData(Database);
        goto repeat;
    }

    if(option == "DELETE" || option == "Delete" || option == "delete")
    {
        int choose;
        cout << "Delete Item No: ";
        cin >> choose;
        Database.erase(Database.begin() + (choose - 1));

        cout << endl;
        ShowData(Database);

        goto repeat;

    }
    if(option == "SEARCH" || option == "Search" || option == "search")
    {
        cout << "Search By [ID, TITLE, YEAR, DEVELOPER, PUBLISHER] : ";
        string choose;
        cin >> choose;
        if(choose == "ID" || choose == "Id" || choose == "id")
        {
            int idNumber;
            cout << "ID No: ";
            cin >> idNumber;
            cout << endl;
            cout << "ITEM NO" << "[" << idNumber << "]" <<endl;
            cout << "    TITLE: " << Database[idNumber - 1].title << endl;
            cout << "     YEAR: " << Database[idNumber - 1].year << endl;
            cout << "DEVELOPER: " << Database[idNumber - 1].developer << endl;
            cout << "PUBLISHER: " << Database[idNumber - 1].publisher << endl;

            goto repeat;
        }
        else if (choose == "TITLE" || choose == "Title" || choose == "title")
        {
            string whatTitle;
            cout << "Enter Title: ";
            cin >> whatTitle;

            for(size_t i = 0; i <= Database.size()-1; i++)
            {
                if(Database[i].title == whatTitle)
                {
                    cout << endl;
                    cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
                    cout << "    TITLE: " << Database[i].title << endl;
                    cout << "     YEAR: " << Database[i].year << endl;
                    cout << "DEVELOPER: " << Database[i].developer << endl;
                    cout << "PUBLISHER: " << Database[i].publisher << endl;
                }
            }
            goto repeat;
        }
        else if (choose == "YEAR" || choose == "Year" || choose == "year")
        {
            int whatYear;
            cout << "Enter Year: ";
            cin >> whatYear;

            for(size_t i = 0; i <= Database.size()-1; i++)
            {
                if(Database[i].year == whatYear)
                {
                    cout << endl;
                    cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
                    cout << "    TITLE: " << Database[i].title << endl;
                    cout << "     YEAR: " << Database[i].year << endl;
                    cout << "DEVELOPER: " << Database[i].developer << endl;
                    cout << "PUBLISHER: " << Database[i].publisher << endl;
                }
            }

            goto repeat;
        }
        else if (choose == "DEVELOPER" || choose == "Developer" || choose == "developer")
        {
            string whatDeveloper;
            cout << "Enter Developer Name: ";
            cin >> whatDeveloper;

            for(size_t i = 0; i <= Database.size()-1; i++)
            {
                if(Database[i].developer == whatDeveloper)
                {
                    cout << endl;
                    cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
                    cout << "    TITLE: " << Database[i].title << endl;
                    cout << "     YEAR: " << Database[i].year << endl;
                    cout << "DEVELOPER: " << Database[i].developer << endl;
                    cout << "PUBLISHER: " << Database[i].publisher << endl;
                }
            }
            goto repeat;
        }
        else if (choose == "PUBLISHER" || choose == "Publisher" || choose == "publisher")
        {
            string whatPublisher;
            cout << "Enter Publisher Name: ";
            cin >> whatPublisher;

            for(size_t i = 0; i <= Database.size()-1; i++)
            {
                if(Database[i].publisher == whatPublisher)
                {
                    cout << endl;
                    cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
                    cout << "    TITLE: " << Database[i].title << endl;
                    cout << "     YEAR: " << Database[i].year << endl;
                    cout << "DEVELOPER: " << Database[i].developer << endl;
                    cout << "PUBLISHER: " << Database[i].publisher << endl;
                }
            }
            goto repeat;
        }
    }
    if (option == "EDIT" || option == "Edit" || option == "edit")
    {
        int whichItem;

        cout << "Enter Item No: ";
        cin >> whichItem;

        cout << endl << "Name: ";
        string name;
        cin >> name;
        Database[whichItem - 1].title = name;
        cout << "Year: ";
        int year;
        cin >> year;
        Database[whichItem - 1].year = year;
        cout << "Developer: ";
        string developer;
        cin >> developer;
        Database[whichItem - 1].developer = developer;
        cout << "Publisher: ";
        string publisher;
        cin >> publisher;
        Database[whichItem - 1].publisher = publisher;
        cout << endl;

        ShowData(Database);

        goto repeat;
    }
    fout.close();   




    system("PAUSE");
    return 0;
}

【问题讨论】:

  • stackoverflow.com/questions/23557071/how-to-read-data-from-a-line-in-a-txt-file-into-a-structure-in-c 的精确副本)

标签: c++


【解决方案1】:

您可以创建一个如here 所示的结构。

在示例中,它们有一个结构数组。要访问结构的元素,请使用 . 运算符。

在 C++11 中,您可以使用 tuple,而不是结构。

Tuple vs Struct - Stackoverflow.

这个想法是第一个可以提供更通用的操作,而第二个具有更好的可读性,恕我直言,您不必记住数据成员的顺序。

[编辑]

正如 R. Hasan 所说,该问题与 this 问题重复。

【讨论】:

  • 没有引入元组作为结构的替代品。
  • 是的,但是可以互换使用它们。我在搜索有关 struct 的内容时发现了 tuple。我觉得很高兴知道。
【解决方案2】:

我不确定这就是您要查找的内容,但请考虑一下(并且不要忘记包含矢量)

首先,我们定义自定义结构

struct Game //your structure
{
    int id;
    std::string title;
    int year;
    std::string developer;
    std::string publisher;
};

现在我们重载 operator>>(类似于使用 cin >> someVariable)。 Fstream 已经有了写入标准类型变量的方法。

bool operator>>(std::fstream& fs, Game& g) 
{
    if (fs >> g.id >> g.title >> g.year >> g.developer >> g.publisher)
        return true;
    return false;
}
/*
fs >> g.id >> g.title equals (fs.operator>>(g.id)).operator>>(g.title) ... 
*/

标准操作符>> 返回对 fstream 的引用,因此我们可以在 1 行代码中编写所有内容。如果写入失败(例如到达文件末尾),我们将返回 false。

std::vector<Game> vec; 

STL vector - 标准容器,包含您的游戏结构

if (fout.is_open())
{
    for ( ; ; )
    {
        Game g; //creating instantiation of your struct Game
        if (fout >> g) //reading from your file
            vec.push_back(g); //1 of STL vector methods, check link to cppreference higher
        else //if reading fails, we break our infinite loop
            break;
    }
}
for (auto x : vec) //going through every element of our vector.
    cout << x.id << " "; //and printing first variable of your structure

【讨论】:

  • @G.Samaras 好吧,我很无聊 - 如果可以的话,为什么不帮助一些人?
  • 不要只给他密码。解释你在做什么,这样就会得到教育。 :) 哦,也许你没有看到我对我的回答的编辑。
  • @G.Samaras 不,我没有:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 2020-07-15
  • 2014-06-09
  • 1970-01-01
  • 2019-08-21
相关资源
最近更新 更多