LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   c++ get() delimiter (http://www.linuxquestions.org/questions/programming-9/c-get-delimiter-213975/)

ashirazi 08-05-2004 05:24 PM

c++ get() delimiter
 
Hi,

If we were reading text would it be possible to set the delimiter to ' ' (space) and '\t' (tabbed space).

Thanks
Shirazi

dakensta 08-05-2004 08:13 PM

Take your pick:

1) int istream::get(char *str, streamsize count, char delim)
2) istream& istream::getline(char *str, streamsize count, char delim)
3) istream& std::getline(istream& strm, string& str, char delim)
4) extraction operator, >>, is whitespace delimited

N.B.
1) does not read delim
2) and 3) do read delim but do not append it to str

(Hope I got that the right way round :p)

ashirazi 08-05-2004 10:02 PM

In

int istream::get(char *str, streamsize count, char delim)

if I wish to delimit space i.e ' ' and tab '\t', how would I go about that. Cause im tryin to read some text and some are spaced and some are tabbed, so if i were to delimit just '\t' the spaced columns would be read as one. I hope you get what im saying...

Thanks
Shirazi

dakensta 08-06-2004 05:26 AM

If you are reading whitespace delimited text, then I wouldn't use get().

This partly depends on the file format and what you want to do with it.
For example, a config or tabular format, I might read into one whole line, using std::getline(istream&, string) and then parse each line into it's constituent parts.

Just for reading a whole load of text though, you could do something like this:

Code:

#include <fstream>      // for std::ifstream, std:: ofstream
#include <iostream>      // for std::cout
#include <string>        // for std::string
#include <vector>        // for std::vector
#include <iterator>      // for std:: ostream_iterator
#include <algorithm>    // for std::copy

using namespace std;

int main()
{
  // First write some text - I have put tab delimited line and space demited
  // lines in
  ofstream ofs("test.txt");
  ofs << "Line one using space\nLine\ttwo\tusing\ttab\t\nLine  three  big  spaces  no  eol";
  ofs.close();

  // Now open the file
  ifstream ifs("test.txt");

  // Create a buffer to read the string
  string tmp;
  // Use a vector to store all the words separately
  vector<string> text;

  // Just keep reading until the end of the file (or an error!)
  // the operator >> will discard anything that it sees as 'whitespace'
  // tab's, spaces, newlines
  while( ifs >> tmp )
    {
      text.push_back(tmp);
    }

  ifs.close();

  // This line will just print out every word to stdout
  // I put the "#\n" bit, appended after each word, so you can see exactly
  // what is in each string (i.e. you will see a '#' at the end of every line)
  copy(text.begin(), text.end(), ostream_iterator<string>(cout, "#\n"));
}



All times are GMT -5. The time now is 12:17 AM.