473,387 Members | 1,456 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Held needed with regards to reading from a file

2
Hi All,

New member here with a bit of problem. I have read the FAQ's and searched text books but still cannot solve the problem that I have.

As part of a course I am doing at University I had to write a program in C++ that would allow the user to enter student information (matriculation number, name, status and mark), which was then stored in an array. They could then search it or list it. Everything was woking (and still is) up to here. We then had to add in two functions that would allow the user to save the array to disk and/or load it back from disk.

I added two functions (included below) int loadFile() and int saveFile() which would load a file from disk or save a file to disk. I can save the file to disk and when looking at the txt file everything appears to be OK. Here is a sample text file that it saves.

Expand|Select|Wrap|Line Numbers
  1. A001
  2. George Price
  3. P
  4. 99
  5. A002
  6. Fred Bloggs
  7. P
  8. 98
  9. A003
  10. Joe Public
  11. F
  12. 40
  13.  
The problem appears to be when I am trying to bring the text file back into the array. It appears that I am only reading the first name of the studentsList[].name
when it should be reading the full line. If I only enter the names as a single name everything works great. Therefore I think the error is in my loadaFile function.

I have tried both

Expand|Select|Wrap|Line Numbers
  1. infile >> studentsList[currentSize].name;
  2.  
  3. // and 
  4.  
  5. getline(infile, studentsList[currentSize].name);
but neither of them will pull in both parts of the name, although the infile option works great for single names.

Here is the code that I think has the problem.
Expand|Select|Wrap|Line Numbers
  1. //declare structure type 
  2.  
  3. struct studentRecord{
  4.     string matricNumber;
  5.     string name;
  6.     string status;
  7.     int mark;
  8.     };
  9.  
  10.     const int listSize = 30;                //number of records in array
  11.     int currentSize;
  12.  
  13. //declare a list of records
  14. studentRecord studentsList[listSize];        //global array of records
  15.  
  16. //function prototypes
  17. void addStudentRecords();
  18. void displayAllRecords();
  19. void displayMenu(int &option);
  20. void searchRecordMenu();
  21. void searchByMatric();
  22. void searchByName();
  23. void displaySearchMenu(int &choice);
  24. int saveFile();
  25. int loadFile();
  26.  
......

Expand|Select|Wrap|Line Numbers
  1. int loadFile()
  2. {
  3.     currentSize = 0;
  4.  
  5.     //open an input file
  6.  
  7.     ifstream infile("c:\\UniWorkspace\\students.txt", ios::in);
  8.  
  9.     // check if file is opened
  10.     if(!infile)                //return true if file is not opened
  11.     {
  12.         cout << "\nFailed to open file !!\n";
  13.         cout << "Press any key to proceed\n";
  14.         cin.get();
  15.         return 1;            //indicate program failed
  16.     }
  17.  
  18.     while(!infile.eof())        //eof() End Of File function. Returns false if the end of file reached
  19.     {
  20.  
  21.             infile >> studentsList[currentSize].matricNumber;
  22.             infile >> studentsList[currentSize].name;
  23. //            getline(infile, studentsList[currentSize].name);    //tried alternate getline as name would normally have space in middle. This didn't work either!!
  24.             infile >> studentsList[currentSize].status;
  25.             infile >> studentsList[currentSize].mark;
  26.  
  27. // The following lines were added to allow me to view the data coming in
  28.  
  29.             cout << "Loop count at " << currentSize << endl;        
  30.             cout << studentsList[currentSize].matricNumber << " "    
  31.                 << studentsList[currentSize].name << " "            
  32.                 << studentsList[currentSize].status << " "            
  33.                 << studentsList[currentSize].mark << endl;        
  34.  
  35. // End of extra line - to be removed once working    
  36.  
  37.             currentSize += 1;            //increment record index
  38.             cout << "\nPress any character to proceed\n";
  39.             cin.get();
  40.     }
  41.  
  42.     infile.close();                //close file
  43.     currentSize = currentSize - 1;
  44.     cout << "\nCurrentSize = " << currentSize << endl;
  45.     cout << "Press any character to proceed\n";
  46.     cin.get();
  47.     return 0;
  48.  
  49. }
  50.  
  51.  
  52. int saveFile()
  53. {
  54.     int i;
  55.  
  56.     //create and open an output stream called students.txt
  57.     ofstream outfile("c:\\UniWorkspace\\students.txt", ios::out);
  58.  
  59.     //check if file is opened
  60.     if(!outfile)                //return true if file is not opened
  61.         {
  62.             cout << "\nFailed to open file!!\n";
  63.             cout << "\nPress any key to proceed ";
  64.             cin.get();
  65.             return 1;
  66.         }
  67.  
  68.     for(i=0; i<currentSize; i++)
  69.         {
  70.             outfile << studentsList[i].matricNumber << endl;
  71.             outfile << studentsList[i].name << endl;
  72.             outfile << studentsList[i].status << endl;
  73.             outfile << studentsList[i].mark << endl;
  74.         }
  75.  
  76.     outfile.close();        //closes file
  77.  
  78.     cout << "\nFile closed" << endl;
  79.     cin.get();
  80.  
  81.     return 0;
  82. }

Thanks in advance..
Geo
Jan 5 '07 #1
2 1718
Ganon11
3,652 Expert 2GB
If you are using getline(infile, stringVariable), it may be retrieving the data from the previous line, which would give it something like A001 for the name. You would have to use an infile.ignore() function call before your getline call. I'm not sure how this would work, though, once you started looping. It might be easier if you declare two string variables - first and last - use infile >> to retrieve these strings, and then concatenate them (with a space between them) to form your overall name variable.
Jan 5 '07 #2
GeoUK
2
Thanks for the fast responce. I have amended the code in the loadFIle() function as follows and it now appears to work.

Expand|Select|Wrap|Line Numbers
  1. infile >> studentsList[currentSize].matricNumber;
  2. infile.get();                                                   //added
  3. getline(infile, studentsList[currentSize].name);    //now gets the line as expected
  4. infile >> studentsList[currentSize].status;
  5. infile >> studentsList[currentSize].mark;
  6.  

Thanks again,

Geo
Jan 5 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: bostonmegarocker | last post by:
Hi to all? For the past couples of weeks I have been programming to make a program that reads a binary file and produces the equivalent text file. The idea is that each byte in the file...
67
by: Steven T. Hatton | last post by:
Some people have suggested the desire for code completion and refined edit-time error detection are an indication of incompetence on the part of the programmer who wants such features. ...
2
by: Parker.Jim | last post by:
I need to write a program which performs word subsitutions on a text file. The program should input the names of three text files: the source file that will be "edited", a text file that contains...
9
by: Arnold | last post by:
I need to read a binary file and store it into a buffer in memory (system has large amount of RAM, 2GB+) then pass it to a function. The function accepts input as 32 bit unsigned longs (DWORD). I...
1
by: Mike Hutton | last post by:
I need some help. I am trying to set up our development environment so as to make life easy for my fellow developers (none of whom have used ASP.NET or VS.NET before). We are developing our...
5
by: Steve | last post by:
Hi, I am sitting down to design our next set of internal apps. I would like to approach this in a way that would allow me to break logical parts of the application that handle specific tasks...
7
by: Parv | last post by:
I am impersoanting a user to an other domain. But while doing so i am getting A required privilege is not held by the client exception. I have tried with aal possible usernames and passwords...
3
by: =?Utf-8?B?Q2hyaXM=?= | last post by:
Hi, I need to store customers and their emails in an XML file for quick lookup in a small program. I am kind of a bit confused with this XML thing. Do I use XML or this XSD Schema? I came up...
3
by: es330td | last post by:
I have a need to transfer a graphic file to a user's system and then access that file. I must have the drive letter:\path location of the file. If at all possible I'd prefer that this not require...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.