0

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].

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Joey
  • 23
  • 1
  • 5
  • 1
    Ok. So what is your question? – Oliver Charlesworth May 24 '12 at 10:01
  • @OliCharlesworth My question is well, how exactly would I go about this? Sorry for not being clear in my initial statement. – Joey May 24 '12 at 10:03
  • @Lap That's a bit of a snide comment for someone who is just looking for help, like I just commented on another answer I'm not looking for a cntrl c/v, I actually trying to understand how to do things... – Joey May 24 '12 at 10:40
  • @Lap: ["As a student, I should get ___a nudge into the right direction___ and ___hints about how to apply my knowledge___, but ___not pasteable answers___."](http://meta.stackexchange.com/a/70155/133368) – sbi May 24 '12 at 14:20

3 Answers3

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.

Component 10
  • 10,247
  • 7
  • 47
  • 64
0

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.
acraig5075
  • 10,588
  • 3
  • 31
  • 50
-1

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();
}
Martol1ni
  • 4,684
  • 2
  • 29
  • 39
  • I do have control of the file, I have spent the best part of an hour trying to research but I think my problem lies in the fact I can't use #include . – Joey May 24 '12 at 10:28
  • Due to limitations put by the lecturer, and before you probably think I'm just trying to find myself an easy cntrl + c/v answer this is needed for a part another code and I just can't figure out how to get it to work... – Joey May 24 '12 at 10:38
  • 1
    Okay. Then next time, add homework tab. And add it in class member function, another list or whatever. :) – Martol1ni May 24 '12 at 10:40
  • Not allowing you to use `std::vector` is not really very realistic since it's actually part of the C++ standard now and you'd *never* implement a vector outside academia, unless there was a very good reason - this isn't it. More to the point, your question gives the impression you want to know how to populate a structure from data in a file. That's what people have spent time to help you do. If the question is really *"How do I implement a collection of a structure"* then that's a seperate issue, so please be clear what you're asking for. – Component 10 May 24 '12 at 10:47
  • @Martol1ni Ahh, will do for next time! Cheers – Joey May 24 '12 at 10:47
  • 4
    [Don't loop while not eof](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – R. Martinho Fernandes May 24 '12 at 13:55