user1733201
user1733201

Reputation: 1

reading records from text file

Ok, im new to c++,but i am doing alot of practicing.

Here is my problem, could someone take a look at my source code, and steer me in the right direction here please.

This is what i'm trying to do.

  1. The program should to be able to read a text file with the records in it.(DID THAT)
  2. I also want to search the records using string in the text file (Haven't done this)
  3. Also, to sort the records from highest to lowest using the decimal numbers or double in text file. I was think of using the bubble sort function.

Here is my code

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

//double gpa;
//string

int main () 
 {
  string line;
  ifstream myfile ("testfile.txt");
  if (myfile.is_open())
 {
    while ( myfile.good() )
 {
      getline (myfile,line);
      cout << line << endl;

 }
    myfile.close();
 }

else cout << "Unable to open file"; 

char c;
cout<<"\n enter a character and enter to exit: ";
cin>>c;
return 0;
}

Here is an exmaple text file with records.

aRecord 90 90 90 90 22.5
bRecord 96 90 90 90 23.9
cRecord 87 90 100 100 19.9
dRecord 100 100 100 100 25.5
eRecord 67 34 78 32 45 13.5
fRecord 54 45 65 75 34 9.84
gRecord 110 75 43 65 18.56

Upvotes: 0

Views: 2776

Answers (1)

LihO
LihO

Reputation: 42083

Note, that getline(myfile, line) might fail, thus it is incorrect to use value of line in that case:

while (myfile.good())
{
    getline(myfile, line);
    cout << line << endl;
}

should be:

while (getline(myfile, line))
{
    cout << line << endl;
}

To your questions 2 and 3: you should try something on your own before asking for help. If not a solution or not even an attempt, then you should have some ideas about it at least. Do you want to go through your text file every time you want to retrieve some data from it? Isn't it better to read it at once and store it in memory (maybe std::vector<Record> and then search for record in vector of records) ? Do you want to go through your file line by line and search some specific string within each line?... Just think more about it and you will find answers to your questions.

Upvotes: 1

Related Questions