Inputting a file into a structure

吃可爱长大的小学妹 提交于 2019-12-11 19:47:50

问题


I am trying to read the lines from a file called 'weapon.txt' and input them into a structure something a long the lines of this

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

The file to be read looks like this:

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

The code I have right now is

#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();
}

EDIT: This is what I have right now after re-doing it, I am getting compile errors of : declaration of 'weapon' as array of references; In function 'void displayfile(...) 'fin' was not declared in this scope; 'weapon' is not declared in this scope; ma,e lookup of 'i' changed for ISO 'for' scoping [-fpermissive].


回答1:


I'd firstly tend to use std::string rather than char arrays - they're just easier to work with. So the structure noww looks like this:

struct weapon
{
    string name;
    int strength;
};

Next you need something that will read the structure from an input stream:

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();
}

Two things here, I've used strtol as a conversion function from string to int. atoi is used but strtol gives you slightly more flexibility and crucially, better error cchecking, alkthough I've not bothered to implement it here. A stringstream might have been another alternative here.

Secondly, I return a boolean indicating whether the name was empty. The reason for this is that when, later in the code, I check for eof() on the ifstream, it isn't actually set until you read past the end of the file. So the last good read will not set it but the first attempt to reead past it will. Returning false here then will indicate to the caller that the 'get' failed due to the ifstream being at end of file.

Lastly, we need something to read all of the weappons in:

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();

This wwill place all the weapons into a vector. Note the call to getWeapon breaks if it failed to prrevent adding on an 'empty' weapon. Not the most glamorous solution but it should work.




回答2:


Pseudo-code goes something like this, (and like Martol1ni has coded for you):

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:


Assuming you control the weapons.txt, don't bother checking for errors in the file, you can do this. Next time, do a little research... :)

#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();
}


来源:https://stackoverflow.com/questions/10735217/inputting-a-file-into-a-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!