473,569 Members | 2,751 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Held needed with regards to reading from a file

2 New Member
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 1734
Ganon11
3,652 Recognized Expert Specialist
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 New Member
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
2007
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 represents a temperature that can only go from 0 to 255. So I start by reading the file in to a character array, and the do an int casting to obtain the...
67
4198
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. Unfortunately these ad hominem rhetorts are frequently introduced into purely technical discussions on the feasibility of supporting such functionality in C++....
2
1765
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 the editing instructions, and a file that will contain the result of the editing.
9
4042
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 can pass a max of 512 words to it at a time. So I would pass them in chunks of 512 words until the whole file has been processed. I haven't worked...
1
1718
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 intranet which will comprise basic content with a number of small data-driven ASP.NET applications. I need to keep things simple, so I need to avoid...
5
1702
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 into modules. For example, assuming we have 4 main tasks to accomplish: - Printing - Editing - Viewing - Inventory Management
7
9747
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 but didn't get success. I am getting same error if i am enetring blank user and password. What i am doing wrong ?
3
1391
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 with this <customers> <customer> <id>1</id>
3
1880
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 user input. (Note that since this is my app and in a corporate network, I have the server in the Trusted Sites zone and every single action is marked...
0
7609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7666
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6278
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.