My problem with getline()

This is a discussion on My problem with getline() within the C++ Programming forums, part of the General Programming Boards category; I dont know if i did it right to make a new thread, because this is the same program but ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    801

    My problem with getline()

    I dont know if i did it right to make a new thread, because this is the same program
    but another problem.

    I got a problem with istream::getline.
    If i use it without the delimiting character its gonna read the whole file so i cant compare word by word the 2 files.
    If i use the delimiting character ' ' space, it wont take in consideration neither the last word of every line ,
    because there is know 'space' after it, nor the first word of every line, because there is no 'space' before it.
    Maybe i should use another function like read() or something?
    Thanks for any input on this.

    Code:
                           
    int main ()
    {
      vector<string> vWords1;
      vector<string> vWords2;
      
      read_file("1.txt", vWords1);
      read_file("2.txt", vWords2);
      
      sort (vWords1.begin(), vWords1.end());
      sort (vWords2.begin(), vWords2.end());
      
      vector<string> v;
      
      set_intersection (vWords1.begin(), vWords1.end(), vWords2.begin(), vWords2.end(), back_ inserter(v));
      
      cout << "Intersection has " << v.size() << " elements.\n";
      for (size_t i = 0; i != v.size(); ++i)
        cout << "The "<< i+1 <<"." << " element is: " << v[i] << "\n";
      
      system("pause");
    }
      void read_file(const char* name, vector<string>& vWords)
      {
        ifstream file(name);
        string line;
        vWords.clear();
        while (getline(file, line, ' ')) {
            vWords.push_back(line);
        }
      }

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    If the words are separated by whitespace (spaces, tabs or newlines) then don't use getline, use operator >>.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    801
    Wow, that was simple. I didnt know we could use oparator>> with fstream. *me ashamed*

    Thank you Daved!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 06:20 AM
  2. Words and lines count problem
    By emo in forum C Programming
    Replies: 1
    Last Post: 07-12-2005, 04:36 PM
  3. getline() problem
    By mrafcho001 in forum C++ Programming
    Replies: 5
    Last Post: 06-12-2005, 02:16 AM
  4. Need help with structures
    By yoursport in forum C++ Programming
    Replies: 8
    Last Post: 04-20-2005, 12:59 PM
  5. getline help
    By ProjectsProject in forum C++ Programming
    Replies: 3
    Last Post: 06-14-2004, 12:12 PM

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