【问题标题】:Inputting a file into a structure将文件输入到结构中
【发布时间】:2012-05-24 10:00:13
【问题描述】:

我正在尝试从一个名为“weapon.txt”的文件中读取这些行并将它们输入到一个结构中,该结构的行数很长

struct weapon
{
    char name[20]; //Edited
    int strength;
}

要读取的文件如下所示:

Excalibur
150
Throwing Stars
15
Rapier
200
Bow and Arrow
100
Axe
200
Crossbow
100
Scimitar
250
Rusted Sword
10
Soul Slayer
500

我现在的代码是

#include<fstream>
#include<iostream>
#include<cstring>

using namespace std;

struct WeaponInfo
{
    char name[16];
    int strength;
};

const int MaxWeap = 10;

void openfile(ifstream&); //Opening the file
void displayfile(ifstream&, WeaponInfo&);//Display file

int main ()
{
    WeaponInfo weapon[MaxWeap];
    ifstream fin;   
    openfile(fin);
    displayfile(fin, weapon[MaxWeap]);  
}


void openfile(ifstream& fin)
{
    fin.open("weapon.txt");
}

void displayfile(ifstream& fin, WeaponInfo& weapon[MaxWeap])
{
    char nm;
    int str;

    while (fin.eof() == 0)
    {
        for(int i = 0; i <= MaxWeap; i++);
        {
            fin.getline(nm);
            fin.getline(str);

            strcpy(weapon[i].name, nm);
            strcpy(weapon[i].strength, str);

            i++;
            cout << weapon[i].name << "\n" << weapon[i].strength << endl;
        }
    }
    fin.close();
}

编辑:这就是我现在在重新做之后所拥有的,我收到以下编译错误:将“武器”声明为引用数组;在函数 'void displayfile(...) 'fin' 未在此范围内声明; 'weapon' 未在此范围内声明; ma,e 查找 'i' 已更改为 ISO 'for' 范围 [-fpermissive]。

【问题讨论】:

标签: c++ file data-structures input ifstream


【解决方案1】:

我首先倾向于使用 std::string 而不是 char 数组 - 它们更易于使用。所以现在的结构是这样的:

struct weapon
{
    string name;
    int strength;
};

接下来,您需要一些可以从输入流中读取结构的东西:

bool getWeapon( ifstream& is, weapon& w )
{
    getline(is, w.name) ;
    string strengthStr;
    getline(is, strengthStr) ;
    w.strength = strtol( strengthStr.c_str(), NULL, 0 );

    return !is.eof();
}

这里有两件事,我使用strtol 作为从字符串到整数的转换函数。使用了atoi,但strtol 为您提供了更多的灵活性,更重要的是,更好的错误检查,尽管我没有费心在这里实现它。 stringstream 可能是这里的另一种选择。

其次,我返回一个布尔值,指示名称是否为空。这样做的原因是,稍后在代码中,当我在 ifstream 上检查 eof() 时,它实际上并没有被设置,直到你读到文件末尾。所以最后一次好的阅读不会设置它,但第一次尝试重新阅读它会。然后在此处返回 false 将向调用者指示由于 ifstream 位于文件末尾而导致“获取”失败。

最后,我们需要一些东西来读取所有的武器:

ifstream input;
input.open("weapons.txt");
vector<weapon> ws;
if ( input )
{
    while (! (input.eof()))
    {
        weapon w;
        if ( ! getWeapon( input, w ) )
            break;

        ws.push_back( w );
    }
}
input.close();

这个w会将所有武器放入一个向量中。请注意,如果无法阻止添加“空”武器,则对 getWeapon 的调用会中断。不是最迷人的解决方案,但它应该可以工作。

【讨论】:

    【解决方案2】:

    伪代码是这样的,(就像 Martol1ni 为你编写的一样):

    open the file
    while (!end-of file)
    {
      create instance of struct weapon
      read a line and strcpy into weapon.name
      read a line and set weapon.strength = atoi(line)
      do something with the instance, eg. add to list, call a member function, etc.
    }
    loop
    close file.
    

    【讨论】:

    • 这看起来很有帮助,谢谢,稍后会回复我的做法:)
    【解决方案3】:

    假设您控制武器.txt,不必费心检查文件中的错误,您可以这样做。下一次,做一点研究... :)

    #include <fstream>
    #include <vector>
    #include <string>
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    struct weapon
    {
    string name;
    int strength;
    weapon(string n, int s) : name(n), strength(s) {}
    };
    
    void readFileToVec(vector<weapon> &myVec) {
        ifstream in("weapon.txt");
        while (!in.eof()) {
            string name;
            getline(in,name);
            string strength;
            getline(in,strength);
            weapon myWep(name,atoi(strength.c_str()));
            myVec.push_back(myWep);
        }
        in.close();
    }
    

    【讨论】:

    • 我确实控制了文件,我花了一个小时的大部分时间来研究,但我认为我的问题在于我不能使用#include 。跨度>
    • 由于讲师的限制,在你可能认为我只是想给自己找一个简单的 cntrl + c/v 答案之前,这是另一个代码的一部分,我只是可以'不知道如何让它工作......
    • 好的。然后下一次,添加作业选项卡。并将其添加到类成员函数、另一个列表或其他任何内容中。 :)
    • 不允许你使用 std::vector 并不是很现实,因为它现在实际上是 C++ 标准的一部分,你永远在学术界之外实现向量,除非有这是一个很好的理由——不是这样。更重要的是,您的问题给人的印象是您想知道如何从文件中的数据填充结构。这就是人们花时间帮助你做的事情。如果问题真的是“我如何实现结构的集合”,那么这是一个单独的问题,所以请清楚你的要求。
    猜你喜欢
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多