Thread: Get stringstream with separator!!!

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    30

    Get stringstream with separator!!!

    I've read some example for the get Int or char for stringstream with ' ' (space) separator.
    for example:
    Code:
    string line = {1 2 3 4 5 6};
    the library will auto get each number as an Int and put into vector
    Code:
    vector<int> numbers;
    The question is "How i get (read) from file and get words
    - space separator
    - "<" or ">" separator (the program will ignore this and assume it as a space)
    - with "-" (hyphen) a numbers of word will become one word (Today-is-a-nice-day) means no separator
    - With "." (end period) - here is a difficult part
    - first: 0.2 0.2a is read by 0.2 and 0.2a
    - second: .2 a.2a .2 (2 spaces) is read by 2 2a and 2 (it will check the char before the "." to be blank.

    Could anyone give me an idea of how to read from a file and get char as description.

    Thanks, regard

  2. #2
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    I'm confused on the first part of your question. However, most of the things you listed below can be solved with getline, which has an option for delimiter
    Code:
    istream& getline (char* s, streamsize n, char delim );
    A good example may be
    Code:
    char name[256];
    ... // file setup
    file.getline(name, 256, '>');
    I hope this helps, but it is hard for me to understand the question.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    30
    Thx for reply. I will explain again.
    this is my text file.
    Code:
    Today!is-not-a-good-day, the<problem<is<this "<"
    More.about.decimal 0.2abc 0.2 .2abc .2 abc.2abc abc.2 abc0.20   .2 . 2
    the requirement of the program is to read the file and then count them

    Code:
    COUNT | WORD
    ------+------
       1  | 0.2
       1  | 0.2abc
       3  | 2
       1  | 20
       2  | 2abc
       1  | More
       1  | Today
       2  | abc
       1  | abc0.20
       1  | about
       1  | decimal
       1  | is
       1  | is-not-a-good-day
       1  | problem
       1  | the
       1  | this
    
    Number of unique words in test.txt is 16
    Total number of words in test.txt is  20
    as you can see as the result. it read each word then count them.
    I wonder should i use string or char to get a word.
    This will involve bintree (which i will read more about). But first i should have an idea of how to make it.
    Thx and regard

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by cubimongoloid
    it read each word then count them.
    What is the definition of word in this context?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    May 2009
    Posts
    30
    is it a vector of char???
    because i confuse to read by line or by char?

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by cubimongoloid
    is it a vector of char?
    No, I am not talking about how you plan to store the words. I am asking about what are the exact rules by which you determine that part of the text forms a word.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    May 2009
    Posts
    30
    As you can read the post above. there is a file with mixing words and chars. The program will read the file, separate them follow the rules (which is show as result, so hard to explain)

    they will be separate by '.'(full stop), space, '<' '>' greater or smaller.
    The '.' has to be distinguished by decimal (0.2 or 3.3 with a.2 or .2 which will become a and 2 or 2)

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    hmm... okay, I missed the part where you expressed the concept in terms of separators rather than the actual definition of a word.

    Either way, here's an idea: define a Word class. Overload operator>> for std::istream for this Word class such that it reads from the input stream into a word. As a prototype implementation, try making it able to read in words separated by spaces, hyphens, '<' and '>'.

    You would also want to overload operator<< for std::ostream to make it easy for you to print the word. Part of your requirements involve implementing a (balanced) binary tree, but for now use a std::map<Word, std::size_t>. Overload operator< for your Word class to make it easy to use it as the key type for std::map (and it will come in handy again when you implement your own binary tree).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    May 2009
    Posts
    30
    thx, im reading and thinking about them.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    To give you a better idea of how this Word class might actually be used, here is an example using std::string:
    Code:
    #include <map>
    #include <string>
    #include <cstddef>
    #include <iostream>
    
    int main()
    {
        typedef std::map<std::string, std::size_t> WordCountMap;
        WordCountMap words;
    
        // Read in the words into the map and update the counts.
        std::string word;
        while (std::cin >> word)
        {
            ++words[word];
        }
    
        // Print the words and their corresponding counts.
        for (WordCountMap::iterator i = words.begin(), end = words.end();
            i != end; ++i)
        {
            std::cout << i->second << ": " << i->first << std::endl;
        }
    }
    With an input of "how much wood would a wood chuck chuck if a wood chuck would chuck wood?" (note that you have to simulate EOF), the expected output would be:
    Code:
    2: a
    4: chuck
    1: how
    1: if
    1: much
    3: wood
    1: wood?
    2: would
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    May 2009
    Posts
    30
    That was quick. I'm just a beginner so to understand it i hv to take time. great work.

    The typedef map<> is in the library or user define. And i havent study map so, i barely understand it. In this case i m forced to use bintree.

    Im trying with the ostream and istream now. This is my attempt
    Code:
    struct words
    {
       string s;
       
       words() : s(" ") {}
       words(const string st) : s(st) {}
       
       friend ostream &operator<< (ostream &stream, words word);
       friend istream &operator>> (istream &stream, words &word);
    };
    
    ostream &operator>> (ostream &stream, words word)
    {
       stream << word.s;
       return stream;
    }
    
    istream &operator<< (istream &stream, words &word)
    {
       stream >> word.s;
       return stream;
    }
    I read by file so i use getline for reading the string and put it into istream
    Code:
    while (fin.good())
          {
             getline(fin, temp);
             words w(temp);
             cout << w;
          }
    now i can work ... just print out text file
    Last edited by cubimongoloid; 05-14-2009 at 11:23 PM.

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by cubimongoloid
    The typedef map<> is in the library or user define. And i havent study map so, i barely understand it.
    std::map is part of the C++ standard library. You can get an overview of its interface from cppreference.com's entries on std::map.

    Quote Originally Posted by cubimongoloid
    In this case i m forced to use bintree.
    std::map is typically implemented with a balanced binary tree. My point here is to use std::map first, then replace it with your own tree implementation later. (Are you sure a bintree must be used? It sounds like it is far more complex than is needed for this problem.)

    Quote Originally Posted by cubimongoloid
    Im trying with the ostream and istream now. This is my attempt
    Looks like you mixed them up. Your declarations should be:
    Code:
    friend ostream& operator<< (ostream &stream, const words& word);
    friend istream& operator>> (istream &stream, words& word);
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    May 2009
    Posts
    30
    I fixed them already, now they can read from file, normal.

    This is base on bintree work with bintree.h is provided by lecturer. He's so tricky. And i'm not sure that can we used another method as map. And there will be only 165 or less code line in this assignment. I don't think it gonna fit.

    Btw, the separator will be define in istream and ostream or getline(fin, temp, '.'). I'm working on it now.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by cubimongoloid
    This is base on bintree work with bintree.h is provided by lecturer.
    Just to clarify: when you say bintree, do you mean the bintree structure as defined by the Dictionary of Algorithms and Data Structures entry that I linked to, or do you merely mean a binary tree, e.g., a simple binary search tree?

    Furthermore, what is the interface of this bintree? Are you supposed to use your lecturer's implementation, or are you supposed to implement it yourself?

    Quote Originally Posted by cubimongoloid
    And i'm not sure that can we used another method as map. And there will be only 165 or less code line in this assignment. I don't think it gonna fit.
    My example was only 24 lines. Adding in the definition of the Word class, plus implementation of operator<< and operator< extended it to a total of 50 lines, including an implementation of operator>> that has no net effect. This leaves you with well over 100 lines to fully implement operator>>, with over a dozen more lines to touch up on your output and cater for a change to use bintree.h instead of <map>. Plus, my indent style consumes a line for each opening brace; changing to use a different indent style can save on lines of code.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    May 2009
    Posts
    30
    I understand what u said. The thing here is the lecturer provide bintree.h and binnode.h (his own work so you have to implement it in to your assignment. Because when submit, i can online submit 1 file then it will be combined with two those file to make the app work.
    bintree.h
    Code:
    #ifndef BINTREE_H_
    #define BINTREE_H_
    
    #include <stdexcept>
    #include <math.h>
    
    #include "binnode.h"
    
    /********************************************************\
       template class for a binary tree
    \********************************************************/
    
    
    template <typename dataType> class bintree
    {
       private:
          binNode<dataType> *root;
          int numItems;
    
       public:
          /*******************************************************\
             constructors & destructors
          \*******************************************************/
    
          // constructor
          bintree() : root(NULL), numItems(0) {}
    
          // destructor
          ~bintree() {
             if (root != NULL) delete root;
          }
    
          /*******************************************************\
             misc functions
          \*******************************************************/
    
          bool empty() const {
             return (numItems == 0);
          }
    
          int size() const {
             return numItems;
          }
    
          int numNodes() const {
             if (root == NULL) {
                return 0;
             } else {
                return root->numNodes();
             }
          }
    
          int maxTreeDepth() const {
             if (root == NULL) {
                return 0;
             } else {
                return root->maxTreeDepth();
             }
          }
    
          int numLeafNodes() const {
             if (root == NULL) {
                return 0;
             } else {
                return root->numLeafNodes();
             }
          }
    
          double balance() const {
             // Returns a measure of how balanced a tree is.
             // A value of 1 is a prefectly balanced tree.
             // The closer to 0 the value is the more unbalanced
             // the tree.
             // A value < 0.5 indicates a tree that is seriously unbalanced
    
             // case of no nodes in tree
             if (numItems == 0) return 1.0;
    
             // calculate balance
             double log2numItems = log10(numItems + 1) / log10(2);
             return log2numItems / maxTreeDepth() * (numLeafNodes() * 2) / (numItems + 1);
          }
    
          void rebalance() {
             // Rebalance tree using the AVL algorithm
             // While this does not guarantee a perfectly balanced tree
             // it does make it mostly balanced by guranteeing that the diference
             // in depth between every right and left subtree is at most 1
    
             if (root != NULL) {
                while (root->rebalance(root));
             }
          }
    
          /*******************************************************\
             insertion and erasure functions
          \*******************************************************/
    
          void insert(const dataType& newData) {
             if (root == NULL) {
                root = new binNode<dataType>(newData);
             } else {
                root->insert(newData);
             }
             numItems++;
          }
    
          void erase(const dataType& delData) {
    
             if (root == NULL) {
                throw std::invalid_argument("data does not exist in tree to erase");
             }
    
             root->erase(&root, delData);
    
             numItems--;
          }
    
          dataType* find(const dataType &findData) const {
                 // this function looks for findData in ther tree.
                     // If it find the data it will return the address of the data in the tree
                     // otherwise it will return NULL
             if (root == NULL) return NULL;
             else return root->find(findData);
          }
    
          /*******************************************************\
             print function for assignment.
                     assumes dataType has print() function
          \*******************************************************/
    
              void print() const {
                 if (root != NULL) root->print();
          }
    };
    
    #endif

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. stringstream problem
    By black_spot1984 in forum C Programming
    Replies: 3
    Last Post: 10-28-2008, 04:09 PM
  2. stringstream clear
    By misterowakka in forum C++ Programming
    Replies: 3
    Last Post: 01-01-2008, 01:03 PM
  3. Socket: send stringstream
    By crisis in forum C++ Programming
    Replies: 5
    Last Post: 11-22-2007, 10:50 AM
  4. static separator
    By Bleech in forum Windows Programming
    Replies: 2
    Last Post: 10-21-2007, 03:47 PM
  5. Length of a stringstream
    By nickname_changed in forum C++ Programming
    Replies: 1
    Last Post: 10-24-2003, 07:30 PM