Having trouble with a assignment.

I have an assignment for beginners c++ class and I need to figure out how to search in a .txt file and search for the specific ID the user enters.

For example the txt file might have.

1234 T-Shirt 24 19.99
2345 Pants 20 15.99
6543 Socks 50 4.99

I'm just haven't figured out how to get to the specific Id when it is in the 2nd or 3rd row and save each individual part on that line to a certain variable.

There is a lot more to the project it just that this one part stops me from continuing.

Again I'm new to C++ so thanks for your comments and suggestions.
You can read each line of the text file until it finds what your looking for; the getline() function is good for this.
Here's a start:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>

using namespace std;

int main( int argc, char * args[] )
{
    fstream fin( "filename" );
    string line;
    while( getline( fin, line ) )
    {
        // parse the line here
    }
    fin.close();
    return 0;
}
I would use a class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class item
{
   public:
     int amount, id;
     string name;
     double price;
};
istream& operator >> ( istream& is, item it )
{
     is >> it.id >> it.name >> it.amount >> it.price; // order has to depend on how the file was written
     return os;
}

int main()
{
     item myitem;
     ifstream file( "myfile" );
     while( !file.eof() )
     {
          file >> myitem;
          if ( myitem.id == the_id_you_want )
          {
               // your operations
          }
     }
}

Last edited on
Topic archived. No new replies allowed.