0

I have created a text file that contains strings and numbers. so I want to make a program that reads these data, but I am stuck in extracting these data and store them into an array of structs..I don't know why it doesn't work... Could anyone help?

Thanks a lot

here is my program:

#include <iostream>
#include <fstream>
using namespace std;

int SIZE = 10;

struct MenuItem
{
    string name;
    float price;
};

float ReadItem( ifstream &in, MenuItem &d )
{
    getline( in, d.name );
    in >> d.price;
    in.ignore();

    return 0;
}

void PrintItem( ostream &out, MenuItem d )
{
    out << "Item name: " << d.name
        << " Price: " << d.price << endl;
    return;
}

int main()
{
    ifstream fin( "text.txt" );
    int i = 0, j;
    MenuItem data[SIZE];

    while( !fin.eof() )
    {
        ReadItem( fin, data[i] );
        i++;
    }

    fin.close();

    for( j = 0; j < i; j++ )
    {
        PrintItem( cout, data[j] );
    }
    return 0;
}
mk250
  • 19
  • 2
  • What do you want to happen, and what is actually happening? Are you getting incorrect output? Compiler errors? Are you stuck on a problem and don't know what to write? – Weak to Enuma Elish Nov 22 '15 at 04:49
  • the output is suppose to be item name and then followed by a price, eg. item1 10.00 item2 9.00 ..... but my output just doesn't come out anything.. I think I am doing wrong in the function that extracts the data, that is in the ReadItem(), but i still can't figure out how to fix it... – mk250 Nov 22 '15 at 05:08
  • Related: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Weak to Enuma Elish Nov 22 '15 at 05:11
  • `while( !fin.eof() )` will allow you to read past the end of the file. Read more: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user4581301 Nov 22 '15 at 05:13
  • It can be tricky to mix `getline` and `>>`. Haven't run your code so you may have it right, but it is tricky regardless. – user4581301 Nov 22 '15 at 05:14
  • Also worth noting that you have no defense against having more than `SIZE` items in the file and overrunning `data`. – user4581301 Nov 22 '15 at 05:16
  • I think you need to step through with a debugger and see where things are going wrong. It might be the format of the text in the file. – Weak to Enuma Elish Nov 22 '15 at 05:18
  • thank you, it works fine now.. – mk250 Nov 22 '15 at 06:26

0 Answers0