Thread: File i/o problem

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    60

    File i/o problem

    Once again hi.
    I tried to write a function getWord that gets a word from a file, but during the compilation i get some errors that i hardly undrestand:
    Code:
    #include <fstream>
    using std::ifstream;
    #include <iostream>
    #include <string>
    using std::string;
    
    string getWord(ifstream file);
    
    int main(){
        char c;
        ifstream file;
        string first;
        file.open("document.txt");
        getWord(file,first);
       std::cout<<"first="<<first<<"\n";   
        return 0;
    }
    string getWord(ifstream file){
           string s;
           char c;
           while(file.get(c)&&c!=' ')
                  s.push_back(c);
           return s;}
    May someone tell me what's wrong with this?

  2. #2
    Registered User rynoon's Avatar
    Join Date
    Dec 2006
    Location
    London, ON
    Posts
    26
    Could you describe the errors?

  3. #3
    Registered User
    Join Date
    Dec 2006
    Posts
    60
    Errors shown below

  4. #4
    Registered User rynoon's Avatar
    Join Date
    Dec 2006
    Location
    London, ON
    Posts
    26
    Your getWord function implementation takes one argument (an ifstream) and in your main you are passing it an ifstream and a string as the second parameter.

  5. #5
    Registered User
    Join Date
    Dec 2006
    Posts
    60
    True, but most errors remain even if i fix it.

  6. #6
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    streams are not copyable.
    You have to pass them as references to functions
    e.g.
    Code:
    string getWord(ifstream & file){
           string s;
           char c;
           while(file.get(c)&&c!=' ')
                  s.push_back(c);
           return s;
    }
    Kurt

  7. #7
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    You must pass file by reference, ie
    Code:
    string getWord(ifstream& file){
           string s;
           char c;
           while(file.get(c)&&c!=' ')
                  s.push_back(c);
           return s;}

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You can't pass an ifstream directly. Pass a reference or a pointer to it.

    If you expect first to be changed by getWord, pass it as a reference or a pointer as well.
    Code:
    #include <fstream>
    using std::ifstream;
    #include <iostream>
    #include <string>
    using std::string;
    
    string getWord(ifstream &file, string &first);
    
    int main(){
        char c;
        ifstream file;
        string first;
        file.open("document.txt");
        getWord(file,first);
       std::cout<<"first="<<first<<"\n";   
        return 0;
    }
    string getWord(ifstream &file, string &first){
           string s;
           char c;
           while(file.get(c)&&c!=' ')
                  s.push_back(c);
           return s;}
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Your function seems unnecessarily complicated. The >> operator would extract the word much more easily and more accurately.

    By getting characters up to a space, however, you don't take into account that there are other types of whitespace that can delimit words - tab character, line feeds. For example, if the file consisted of lines, each having one word, the getWord function would return the whole file contents.

    It all could be as simple as:
    Code:
    bool getWord(ifstream &file, string& s)
    {
        return file >> s;
    }
    where the return value indicates if the input operation was successful.

    However, if the function does something so basic, is it even needed? Wouldn't it be less trouble to write
    Code:
        file >> first;
    
    //or
        while (file >> first) {
    instead of the function call?

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Perhaps it's an assignment.

    Instead of comparing the character to ' ', use isspace() in <cctype>, which considers spaces, newlines, carriage returns, form feeds, vertical tabs, and all sorts of things in the C locale.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #11
    Registered User
    Join Date
    Dec 2006
    Posts
    60
    Thanks a lot for your answers..
    I understand what i was doing wrong.

  12. #12
    Registered User
    Join Date
    Dec 2006
    Location
    Scranton, Pa
    Posts
    252
    Code:
    int main () 
    {
        char filename[24];
        ifstream MyFile;
        cout<<"enter filename";
        cin>> filename;
        MyFile.open(filename, ios::in);
         if (MyFile.good());
          {
          cout<<"good open\n";
          }
      while (!MyFile.eof())
      {
        string ws_left, word; //whitespace
        getline(MyFile,ws_left,' ');
       MyFile>>word;
     
     ofstream out("output.txt",ios::out |ios::app);
     out<<word<<" ";
    
    }
     MyFile.close();
     out.close();
     cin.get();
     return 0;
       
    }
    *Edit, I see you've already solved your problem. Oh well....
    Last edited by Oldman47; 12-30-2006 at 06:45 PM.

  13. #13
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Oldman, your code has several errors and problems - did you compile and run it?

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main () 
    {
        char filename[24]; /*Better use std::string,
            at least 256 characters should be allowed anyway */ 
    
        ifstream MyFile;
        cout<<"enter filename";
        cin>> filename;
        MyFile.open(filename.c_str(), ios::in);
        if (MyFile.good());/*because of the semicolon!
            the following block is always executed.
            Why don't you do anything if the file couldn't be opened? */
        {
            cout<<"good open\n";
        }
        while (!MyFile.eof()) //bad way to control input loop
        {
            string ws_left, word; //whitespace
    
            /*What do you expect to happen here?
            This will just skip some words?*/
            getline(MyFile,ws_left,' ');
            MyFile>>word;
            
        //why not open the file once outside the loop?
            ofstream out("output.txt",ios::out |ios::app);
            out<<word<<" ";
        
        }
        MyFile.close();
        out.close(); //out is out of scope here
        cin.get(); //Won't stop because the input buffer has a leftover endline 
        return 0;
    
    }

  14. #14
    Registered User
    Join Date
    Dec 2006
    Location
    Scranton, Pa
    Posts
    252

    Talking

    Quote Originally Posted by anon
    Oldman, your code has several errors and problems - did you compile and run it?

    No, just wrote it in. Gotta cut an 'old man' some slack. Below compiles:

    Code:
    #include <iostream>
    #include <string>
    #include <fstream>
    
    
    using namespace std;
    int main () 
    {
        char filename[24];
        ifstream anyfile;
        std::cout<<"enter filename";
        std::cin>> filename;
        anyfile.open(filename);
         if (anyfile.good());
          {
          cout<<"good open\n";
          }
      while (!anyfile.eof())
      {
       string ws_left, word; //whitespace
        getline(anyfile,ws_left,' ');
        anyfile>>word;
        std::cout<<word<<"\n";
        if (ws_left!=" ")
        {
     ofstream out("new.txt", ios::out| ios::app);
     out<<ws_left;
       }
        if (word.size()>=1)
        {
     ofstream out("new.txt", ios::in| ios::out | ios::app);
     out<<word<<" ";
    }
    }
     anyfile.close();
     std::cout<< "\n";
     getch();
     return 0;
       
    }
    As far as the use of other 'bad code', I am aware of it, though it was just an example. I used bad code in the latter example too, but yet it worked.

    In the future I'll refrain from presenting such sloppy work.

    Quote Originally Posted by anon
    What do you expect to happen here?
    This will just skip some words?*/
    getline(MyFile,ws_left,' ');
    MyFile>>word;

    //why not open the file once outside the loop?
    Actually the first code would only skip the 1st word if there was no leading whitespace, but basically yea, the code wasn't (and still isn't) well structured. As to ; 'why not open the file once outside the loop?', uh hu, that'd be the smart thing to do.

    I just started coding again after 20+yrs away from it and back then it was Dos, so you can well imagine that my skills are not what they should be.
    Last edited by Oldman47; 12-31-2006 at 06:22 PM.

  15. #15
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Your getline + >> idea adds a whole lot of complexity. If you just want to copy each word to another file, separated by a space, you don't need anything more than:
    Code:
    ifstream in(inputfile);
    ofstream out(outputfile);
    //check if good, and don't proceed if not
    string word;
    while (in >> word) {
        out << word << " ";
    }
    >> operator discards whitespace automatically, you don't need to write any code to do that

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  2. File I/O problem
    By Onions in forum C++ Programming
    Replies: 41
    Last Post: 02-24-2006, 04:32 PM
  3. File I/O problem
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 12
    Last Post: 09-03-2005, 12:14 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM