Thread: C++ question about an example taken from cplusplus.com

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    1

    Post C++ question about an example taken from cplusplus.com

    This is kind of awkward because I took this example from another site, but I like this forum more. (I use both sites for reference though). Anyways- I have a question about this code:

    Code:
    /* strtok example */
    #include <stdio.h>
    #include <string.h>
    #include <iostream>
    #include <cstdlib>
    #include <string>
    
    int main ()
    {
      char str[] ="- This, a sample string.";
      char * pch;
      printf ("Splitting string \"&#37;s\" into tokens:\n",str);
      pch = strtok (str," ,.-");
      while (pch != NULL)
      {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
      }
      system("PAUSE");
      return 0;
    }
    printf ("Splitting string \"%s\" into tokens:\n",str); \\ this is what confuses me. What the is \"%s\" used for? Another question that I have is why is his sample string a char?


    I'm a noob but I'm trying to complete a project that I designed for myself. I'm having a hard time splitting strings into tokens or arrays and finding bits of information. My finished product would hopefully do this:

    1) ask a question (an essay question that has multiple answers)
    2) receive input
    3) search input for possible answers
    4) let the user know whether he/she is correct

    I need help with #3; what are my options for functions/methods?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    \" - escape sequense to print a " character

    &#37;s - format to print a nul-terminated string passed as a parameter
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    First of all, Welcome to Programming!

    Secondly, I don't think I would be comfortable letting you take that code sample and try to learn from it. It is a very confusing piece of code as it has a lot of mixing of "standards" between C and C++. While some may say that is fine, I think for someone starting out it will be more confusing than anything.

    For your question on searching for answers:

    If you are going in the C++ direction, you can use the String class (this is the <string> header you have in that code, not the <string.h>) The string class has a find method so you could do something like:

    Code:
    #include <iostream>
    #include <string>   // header for the string class
    
    // careful with this one (see FAQs)
    using namespace std;
    
    int main()
    {
        string sentence;    // string to search
        string search;      // what to search for
    
        // this will be where the search found something
        string::size_type search_result;
    
        // get the sentence
        cout << "Enter a sentence: ";
        getline(cin, sentence);
    
        // get the search term
        cout << "Enter a term to search for: ";
        getline(cin, search);
    
        // search sentence for the search term starting at the begining
        search_result = sentence.find(search, 0);
    
        // if the term was not found it will return string::npos
        if(search_result != string::npos) {
            cout << "Found " << search << " at " << search_result;
        }
        else
        {
            cout << "Could not find " << search;
        }
    
        return 0;
    }
    That should have all the elements to accomplish what you need to do. If there are things you don't understand look around on the forums and look in the FAQs. If you are still unsure about how something works, try to make a test program that uses it. If you still are unsure post some code that shows how you are trying to use it and then ask questions!


    Quote Originally Posted by strbits View Post
    printf ("Splitting string \"&#37;s\" into tokens:\n",str); \\ this is what confuses me. What the is \"%s\" used for? Another question that I have is why is his sample string a char?
    As vart described, the \ in literal strings are excape characters that let you do different things. In this case the \" lets the compiler know that this is to include the " in the string and that it's not trying to end that string in the editor. The %s is replaced with the value of str becasue it's passed as the argument in the printf statement. In C and often times in C++ "strings" are simply character arrays. I have not dwelled too deeply into this before, but I believe the C++ string class essentially is some fancy dressing on a const char array that can make your life easier. I may be wrong on that though.
    Last edited by Vicious; 03-26-2008 at 02:54 PM.
    What is C++?

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    but I believe the C++ string class essentially is some fancy dressing on a const char array that can make your life easier. I may be wrong on that though.
    not a const - because you can write to it (to the class, not to the underlying array directly)

    and the class actually wraps dynamically allocated array of chars - growing string as needed and removing from the used the headake of reallocing array as string grows

    also standard does not require that the internal storage be continues - so the string could actually consist of several "frames"
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  5. #5
    The larch
    Join Date
    May 2006
    Posts
    3,573
    But Vicious, your example is nothing even close to splitting a string into words.

    Another question that I have is why is his sample string a char?
    This is not a char but an array of char's, AKA a C-style string.
    There doesn't seem to be a standard C++ function that splits a string into words, therefore a standard C function is used for that. And these, naturally, only work with C style strings.
    (Of course, you could write your own strtok for std::string.)

    1) ask a question (an essay question that has multiple answers)
    2) receive input
    3) search input for possible answers
    4) let the user know whether he/she is correct
    Are you saying that you want to program a computer to understand English well enough to determine whether an open-ended question was answered correctly? I would imagine that breaking input into words is the smallest of your problems...
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  6. #6
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    I know I didn't break the tring into tokens, but I was just giving some code based on the 4 items requested by the OP.
    What is C++?

  7. #7
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    There doesn't seem to be a standard C++ function that splits a string into words
    operator>> is part of the standard...
    Code:
    #include <sstream>
    #include <iostream>
    
    int main()
    {
    	std::stringstream ss("This is a sample string that was read from user");
    	std::string word;
    	while(ss>>word)
    	{
    		std::cout << word << std::endl;
    	}
    	std::cout << std::endl;
    	return 0;
    }
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  8. #8
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    And there's lots of options in Boost. Boost.Tokenizer is very nice. Boost.String_Algo has split() algorithms.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  9. #9
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Quote Originally Posted by vart View Post
    operator>> is part of the standard...
    Yes, but it is not so easy when you also take punctuation marks into account.

    Boost is definitely worth getting for this.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM