ifstream with getline?

This is a discussion on ifstream with getline? within the C++ Programming forums, part of the General Programming Boards category; Hey I am having trouble with the syntax for a program i have to write. I am still learning so ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    10

    ifstream with getline?

    Hey I am having trouble with the syntax for a program i have to write. I am still learning so go easy on me . I am trying to recover information from a simple text file into a number of arrays using a for loop.

    This is the load function im having trouble with.
    Code:
    void load()
    {
    	int i;
    	char *rcrdpnt;
    	ifstream fin("data.dat");
    	for (i=0; i<100; i++)
    	{
    		fin.getline( *rcrdpnt)
    		rcrdpnt=(entry[i].name)
    		//fin.getline(entry[i].street);
    		//fin.getline(entry[i].streetii);
    		//fin.getline(entry[i].postcode);
    	}
    }//end function
    This is the save function which delimits with /n this works

    Code:
    void save(int i)
    {
    	ofstream fout("data.dat", ios::app); // opens file data.dat for output to the program in append mode.
    	fout << (entry[i].name) << "\n"; // puts name variable of number [i] into a file then starts new line
    	fout << (entry[i].street) << "\n";
    	fout << (entry[i].streetii) << "\n";
    	fout << (entry[i].postcode) << "\n";
    	fout.close();
    }// End of Function
    I cant seem to work out the syntax I want it to read a whole line from a file into the arrays entry[i].name, entry[i].street, etc. I tried directly using the variable names and using a pointer. Its my understanding you write it in this context

    fin.getline(variableorpointer, maxamounttoread, delimiting char);

    if the delimiting character is not specified it automatically uses /n as the delimiter.
    However no matter how much i shift it about it wont compile
    I am using VC++ 6 to compile and my lecturer just can't seem to teach. I think its a language barrier thing (He's Iranian i think), also we seem to learning some arcaic form of C++ so Iv'e been trying learn as much as i can on my own. please explain in simple terms I am a noob.

    PS I know it should be int main () but my lecturer insists we use void main (void) yes I want to slap him too y would he be teaching us this?

    Any help would be much appreciated
    Last edited by DigiAcid; 03-06-2009 at 05:30 AM. Reason: Fluffed it

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    2,144
    if they're forcing you to use VC++ 6, you need to inform them that it's not even standard C++. I suspect they're still telling you to include iostream.h.

    in response to your problem, are you allowed to use std::string, or are you required to use char arrays? if you're allowed to use string, you can use the std::getline function (different from the istream::getline function).

    Code:
    std::string s;
    std::getline(fin, s);
    Also, I don't see you declaring 'entry' anywhere. I suspect that it's supposed to be declared as

    Code:
    char* entry[MAXLINES];
    but the compiler won't be able to make such a guess.

    my suggestion is to use a vector<std::string> instead of an array of char arrays, and std::getline.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,968
    Quote Originally Posted by DigiAcid
    if the delimiting character is not specified it automatically uses /n as the delimiter.
    However no matter how much i shift it about it wont compile
    So you know that this version of getline() takes three arguments, with one of them being optional. However, your example code uses getline() with only one argument. Surely an argument is missing? Furthermore, this version of getline() reads into a char array, but you provide it with a char, not a pointer to the first element of a char array.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    10
    std::string may as well be foreign to me lol
    I have seen it about everywhere but I havent been taught it
    I will post my entire code to avoid confusion.
    the array entry[i].name is declared globally after the struct.
    Our uni is too cheap to get the new VS package cant even see y we are learning c++ as I am learning B(sc) electronic control systems and embedded systems are usually programmed in c. so ???. anyways thats a different subject altogether lol.
    heres my entire code so far.

    Code:
    #include "stdafx.h"
    #include "iostream.h"
    #include "fstream.h"
    #include "stdlib.h" // includes standard libary header for clear screen function
    #include "string.h"
    struct record {                  /*struct called record*/
    			char name[30];
    	        char street[50];
                char streetii[50];
                char postcode[10];
    			};
    
    record entry[100];       /* delares variable entry with max 100 records*/
    
    //entry(input);
    void main(),menu(),options(int choice);
    void newrecord(),deleterecord(),findrecord(),displayall(),exit();
    void dofirst(), load(), input(),save(int i); 
    int find_free();
    
    void main ()
    {
    dofirst();
    menu();
    }
    void menu()
    {
         int choice; //declares the choice variable,
         do
         {
              cout << "Which option would you like? (1-5) \n\n";
              cout << "1: New Entry In Database\n";
              cout << "2: Delete Entry In Database\n";
              cout << "3: Find and Display A Single Record\n";
              cout << "4: Display All Records\n";
              cout << "5: Exit Database\n";
    		  cout << "\nPlease Enter Your Choice (1-5): ";//Display some options on screen.
                 
    		  cin  >> choice;
         
    		  options(choice); //opens options function + sends choice to options function.
    
         }while(choice!=5);//The program will continue to run until option 5 (exit) is chosen.
    }//end function
    
    void options(int choice)
    {
         switch (choice)//Goes Through options
         {
              case 1:  //If number 1 is picked, it will go to the function below same each case. 
                   newrecord();
                   break;
              case 2:
                   deleterecord();
                   break;
              case 3:
                   findrecord();
                   break;
              case 4:
                   displayall();
                   break;
              case 5:
                   exit();
                   break;
              default://THEY DIDNT READ THE MENU, Make Them Choose Correct choice
                  system("cls"); // Clear Screen
    			  cout << "\a\a\a\nYOU HAVE ENTERED AN INVALID CHOICE YOU FOOL!\n"
    				    << "Please enter a number from 1 to 5\n\n";
    			  // shown if an incorrect choice is shown.
    			  break;
         }
    }//end function
    
    //functions
    
    
    void dofirst() // this function prepares the data.dat file for first use
    {
    int i; // variable i declared
    	for ( i=0; i<100; i++ ) // loop until i=99
    	{
    		cout << "Preparing Record Line " << i << "\n" << endl; // shows progress of file prep
    		system("cls"); // clear screen
    		strcpy(entry[i].name, "*"); // make entry[i].name in struct/array = *
    	}
    load();
    } //end function
    
    void newrecord()
    {	
    	input(); // calls the input function 
    	system("cls"); // clear screen
    }//end function
    
    void input()
    {
    
    int i;	
    i=find_free();
    
    	if (i==-1) // if find_free fuction returns -1 do below
    	{	
    		system("cls");	
    		cout << "THE DATABASE IS FULL PLEASE DELETE SOME RECORDS\n\n";
    	}
    	else 
    	{
    	system("cls"); //clear screen
    	
    	cout <<"Enter Name:" << endl;
    	gets((entry[i].name));
    	cout <<"Enter House number and street address: " << endl;
    	gets((entry[i].street)); 
    	cout <<"Enter Town/City: " << endl;
    	gets((entry[i].streetii));
    	cout <<"Enter Post Code:" << endl; 
    	gets((entry[i].postcode));
    	save(i); //calls 
    	}
    }//end function
    
    int find_free()
    {
    int i;
    	for ( i=0; i<100; i++) //loops until i is = 99
    	{
    	if (!strcmp ((entry[i].name), "*")) //if String * is the same as, entry.name of number i return true
    	return i; // if strcmp statement is true return i to the function that called findfree()
    	}
    return -1; //if the above for statement finds nothing then return -1 to the calling funtion. 
    }//end function
    
    void exit()
    {
    	system("cls");
    	cout << "\nThankyou For Using Jays' Database. Goodbye :)\n\n";
    }//end function
     
    
    void load()
    {
    	int i;
    	char *rcrdpnt;
    	ifstream fin("data.dat");
    	for (i=0; i<100; i++)
    	{
    		fin.getline( *rcrdpnt)
    		rcrdpnt=(entry[i].name)
    		//fin.getline(entry[i].street);
    		//fin.getline(entry[i].streetii);
    		//fin.getline(entry[i].postcode);
    	}
    }//end function
    
    void save(int i)
    {
    	ofstream fout("data.dat", ios::app); // opens file data.dat for output to the program in append mode.
    	fout << (entry[i].name) << "\n"; // puts name variable of number [i] into a file then starts new line
    	fout << (entry[i].street) << "\n";
    	fout << (entry[i].streetii) << "\n";
    	fout << (entry[i].postcode) << "\n";
    	fout.close();
    
    }//end function
    
    void findrecord()
    {
    //	int i;
    	system("cls");
    }//end function
    
    void displayall()
    {
    	system("cls");
    	cout << "free function\n\n";
    }//end function
    void deleterecord()
    {
    	system("cls");
    	cout << "free function 2\n\n";
    }//end function
    Yeh we are using iostream.h vc++ 6 doesnt understand iostream

    Its the load function that Im having trouble with

  5. #5
    Registered User
    Join Date
    Mar 2009
    Posts
    10
    Yeh Im sorry I didn't leave the code in a very good state. I will clean it up

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,968
    Quote Originally Posted by DigiAcid
    Yeh we are using iostream.h vc++ 6 doesnt understand iostream
    It does, at least from what I remember. Microsoft Visual C++ 6 is pre-standard, but it does include some support for the C++ standard. In this case I think that the problem is with your code (see my post #3), not the compiler.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Oct 2008
    Posts
    115
    laserlight means that you're having problem with getline.

    Compare your getline to the getline documentation right here

  8. #8
    Registered User
    Join Date
    Mar 2009
    Posts
    10
    Thanks everyone for you advice so far I have checked that site out before and I couldnt figure out the syntax
    this is what I was trying before I started wildly guessing

    Code:
    void load()
    {
    	int i;
    	char *rcrdpnt;
    	ifstream fin("data.dat");
    	for (i=0; i<100; i++)
    	{
    		fin.getline((entry[i].name), 30, "\n");
    		//rcrdpnt=(entry[i].name)
    		//fin.getline(entry[i].street);
    		//fin.getline(entry[i].streetii);
    		//fin.getline(entry[i].postcode);
    	}
    }//end function
    which gives me this error
    Assignment 2.cpp(147) : error C2664: 'class istream &__thiscall istream::getline(char *,int,char)' : cannot convert parameter 3 from 'char [2]' to 'char'
    This conversion requires a reinterpret_cast, a C-style cast or function-style cast
    Looking at this I though ok so its saying something about char *? so I tried a pointer to the variable (entry[i].name) instead, shown below.
    Code:
    void load()
    {
    	int i;
    	char *rcrdpnt[30];
    	ifstream fin("data.dat");
    	for (i=0; i<100; i++)
    	{
    		fin.getline(char *rcrdpnt, 30, "\n");
    		*rcrdpnt=(entry[i].name);
    		//fin.getline(entry[i].street);
    		//fin.getline(entry[i].streetii);
    		//fin.getline(entry[i].postcode);
    	}
    }//end function
    this gave me these errors
    Assignment 2.cpp(147) : error C2144: syntax error : missing ')' before type 'char'
    Assignment 2.cpp(147) : error C2661: 'getline' : no overloaded function takes 0 parameters
    Assignment 2.cpp(147) : error C2059: syntax error : ')'
    I am sure Im on the right track but I just can't figure out what im doing wrong!
    Thanks Again

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,968
    Look carefully at the error message: "cannot convert parameter 3 from 'char [2]' to 'char'".

    Basically, you are supplying a string literal where you are supposed to supply a char, i.e., you should write '\n' instead of "\n".
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Mar 2009
    Posts
    10
    Ah ha! you are genius I love you! I was about to have serious words with my laptop screen

    SO just so I know for the future " " means? and ' ' means??
    whats the difference between the 2?

    thanks so much for your help

  11. #11
    Registered User
    Join Date
    Mar 2009
    Posts
    10
    hmm however now my find_free function seems to have stopped working properly, as the input function is having i returned as -1 all the time and saying all records are full :S odd
    seems to be ok?
    Any ideas why the load function would do that?
    Code:
    #include "stdafx.h"
    #include "iostream.h"
    #include "fstream.h"
    #include "stdlib.h" // includes standard libary header for clear screen function
    #include "string.h"
    struct record {                  /*struct called record*/
    			char name[30];
    	        char street[50];
                char streetii[50];
                char postcode[10];
    			};
    
    record entry[100];       /* delares variable entry with max 100 records*/
    
    //entry(input);
    void main(),menu(),options(int choice);
    void newrecord(),deleterecord(),findrecord(),displayall(),exit();
    void dofirst(), load(), input(),save(int i); 
    int find_free();
    
    void main ()
    {
    dofirst();
    menu();
    }
    void menu()
    {
         int choice; //declares the choice variable,
         do
         {
              cout << "Which option would you like? (1-5) \n\n";
              cout << "1: New Entry In Database\n";
              cout << "2: Delete Entry In Database\n";
              cout << "3: Find and Display A Single Record\n";
              cout << "4: Display All Records\n";
              cout << "5: Exit Database\n";
    		  cout << "\nPlease Enter Your Choice (1-5): ";//Display some options on screen.
                 
    		  cin  >> choice;
         
    		  options(choice); //opens options function + sends choice to options function.
    
         }while(choice!=5);//The program will continue to run until option 5 (exit) is chosen.
    }//end function
    
    void options(int choice)
    {
         switch (choice)//Goes Through options
         {
              case 1:  //If number 1 is picked, it will go to the function below same each case. 
                   newrecord();
                   break;
              case 2:
                   deleterecord();
                   break;
              case 3:
                   findrecord();
                   break;
              case 4:
                   displayall();
                   break;
              case 5:
                   exit();
                   break;
              default://THEY DIDNT READ THE MENU, Make Them Choose Correct choice
                  system("cls"); // Clear Screen
    			  cout << "\a\a\a\nYOU HAVE ENTERED AN INVALID CHOICE YOU FOOL!\n"
    				    << "Please enter a number from 1 to 5\n\n";
    			  // shown if an incorrect choice is shown.
    			  break;
         }
    }//end function
    
    //functions
    
    
    void dofirst() // this function prepares the data.dat file for first use
    {
    int i; // variable i declared
    	for ( i=0; i<100; i++ ) // loop until i=99
    	{
    		cout << "Preparing Record Line " << i << "\n" << endl; // shows progress of file prep
    		system("cls"); // clear screen
    		strcpy(entry[i].name, "*"); // make entry[i].name in struct/array = *
    	}
    load();
    } //end function
    
    void newrecord()
    {	
    	input(); // calls the input function 
    	system("cls"); // clear screen
    }//end function
    
    void input()
    {
    
    int i;	
    i=find_free();
    
    	if (i==-1) // if find_free fuction returns -1 do below
    	{	
    		system("cls");	
    		cout << "THE DATABASE IS FULL PLEASE DELETE SOME RECORDS\n\n";
    	}
    	else 
    	{
    	system("cls"); //clear screen
    	
    	cout <<"Enter Name:" << endl;
    	gets((entry[i].name));
    	cout <<"Enter House number and street address: " << endl;
    	gets((entry[i].street)); 
    	cout <<"Enter Town/City: " << endl;
    	gets((entry[i].streetii));
    	cout <<"Enter Post Code:" << endl; 
    	gets((entry[i].postcode));
    	save(i); //calls save
    	}
    }//end function
    
    int find_free()
    {
    int i;
    	for ( i=0; i<100; i++) //loops until i is = 99
    	{
    	if (!strcmp ((entry[i].name), "*")) //if String * is the same as, entry.name of number i return true
    	return i; // if strcmp statement is true return i to the function that called findfree()
    	}
    return -1; //if the above for statement finds nothing then return -1 to the calling funtion. 
    }//end function
    
    void exit()
    {
    	system("cls");
    	cout << "\nThankyou For Using Jays' Database. Goodbye :)\n\n";
    }//end function
     
    
    void load()
    {
    	int i;
    	ifstream fin("data.dat");
    	for (i=0; i<100; i++)
    	{
    		fin.getline((entry[i].name), 30, '\xba');
    		fin.getline((entry[i].street), 50, '\xba');
    		fin.getline((entry[i].streetii), 50, '\xba');
    		fin.getline((entry[i].postcode), 10, '\xba');
    	}
    }//end function
    
    void save(int i)
    {
    	ofstream fout("data.dat", ios::app); // opens file data.dat for output to the program in append mode.
    	fout << (entry[i].name) << "\xba"; // puts name variable of number [i] into a file then starts new line
    	fout << (entry[i].street) << "\xba";
    	fout << (entry[i].streetii) << "\xba";
    	fout << (entry[i].postcode) << "\xba\n";
    	fout.close();
    
    }//end function
    
    void findrecord()
    {
    //	int i;
    	system("cls");
    }//end function
    
    void displayall()
    {
    	system("cls");
    	cout << "free function\n\n";
    }//end function
    void deleterecord()
    {
    	system("cls");
    	cout << "free function 2\n\n";
    }//end function

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,968
    Quote Originally Posted by DigiAcid
    SO just so I know for the future " " means? and ' ' means??
    whats the difference between the 2?
    The former is used to delimit (as in "quote") string literals while the latter is used to delimit character literals.

    You still need to indent your code properly.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Dec 2008
    Posts
    65
    From what I can tell, after sorting out your indentation issues, is this:

    in your dofirst() function (which could probably be a default constructor) you set name to "*", after that you load data from (probably, but even if it wasn't) an empty file, overwriting the "*" with garbage or '\0', so when you compare your strings, name is '\0' so the function returns -1.

    hope that helps, you might want to consider using std::string.

  14. #14
    Registered User
    Join Date
    Mar 2009
    Posts
    10
    how do you mean indent my code. Hmm silly me should have thought of that.
    Back to the drawing board I guess. lol

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getline() don't want to work anymore...
    By mikahell in forum C++ Programming
    Replies: 7
    Last Post: 07-31-2006, 10:50 AM
  2. problem with string class, ifstream, and getline
    By deathbob in forum C++ Programming
    Replies: 9
    Last Post: 09-18-2005, 11:20 AM
  3. ifstream getline
    By jimboob in forum C++ Programming
    Replies: 2
    Last Post: 09-25-2004, 10:37 AM
  4. getline() and ifstream
    By quizkiwi in forum C++ Programming
    Replies: 5
    Last Post: 08-31-2004, 01:44 PM
  5. getline help
    By ProjectsProject in forum C++ Programming
    Replies: 3
    Last Post: 06-14-2004, 11:12 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21