C++ question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gimp
    Registered User
    • Jan 2001
    • 2368

    #1

    C++ question

    All right, I'm to lazy to figure this out myself. I need to read in the date. someone would type "03/23/02", and I need to store the 3 in a month variable, the 23 in day, and the 02 in year. I have some ideas on how to do this, but is there some really easy way?
  • dave_p

    #2
    you can take the input as a string and use strtok() function to break it up int 3 tokens using the / as your delimiter. then convert each token to int and store it in its own variable: int mon int day int year the user has to be consistent about the format of their input though and a lot of error checking will be necessary for dolt users(entering date different than requested).

    you could write your own date class that will prompt for input and display formatted output and store each part of the date in its own class variable.

    you can try screwing around with the C++ date and time classes.

    you will learn the most by doing all three and seeing which is more elegant for your purposes.

    Comment

    • beam
      The end.
      • May 2001
      • 2036

      #3
      just ask for it in the mm/dd/yy format and then do a "split" on the string.

      look in your book for the split function...it takes a string and a character as parameters. the string is the string you want to split, the character is the character you want to split on.

      like this... date_array = split(date_string, "/")

      the result is an array with the month in date_array[0], day in date_array[1], and year in date_array[2]

      now, this is my disclaimer....I DON'T KNOW C++!!! hahaha
      but it is a high-level language so i would assume it would have a split function.

      good luck
      <---Should be banned for circumventing the cuss filter.

      Comment

      • dave_p

        #4
        split would be an excellent choice, but its a visual basic function, not C++.
        if it was available it would be the one to use though! strtok() is similar with the exception of the array part, which can easily be coded in. below are excerpts from MSDN on both functions:

        Split
        Returns a zero-based, one-dimensional array containing a specified number of substrings.

        Syntax
        Split(expression[, delimiter[, count[, compare]]])

        The Split syntax has these parts:

        Part Description
        expression Required. String expression containing substrings and delimiters. If expression is a zero-length string, Split returns an empty array, that is, an array with no elements and no data.
        delimiter Optional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
        count Optional. Number of substrings to be returned; -1 indicates that all substrings are returned.
        compare Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.


        Settings
        The compare argument can have the following values:

        Constant Value Description
        vbBinaryCompare 0 Perform a binary comparison.
        vbTextCompare 1 Perform a textual comparison.
        vbDatabaseCompare 2 Perform a comparison based on information contained in the database where the comparison is to be performed.


        strtok() Remarks

        The strtok function finds the next token in strToken. The set of characters in strDelimit specifies possible delimiters of the token to be found in strToken on the current call. wcstok and _mbstok are wide-character and multibyte-character versions of strtok. The arguments and return value of wcstok are wide-character strings; those of _mbstok are multibyte-character strings. These three functions behave identically otherwise.

        Generic-Text Routine Mappings

        TCHAR.H Routine _UNICODE & _MBCS Not Defined _MBCS Defined _UNICODE Defined
        _tcstok strtok _mbstok wcstok


        On the first call to strtok, the function skips leading delimiters and returns a pointer to the first token in strToken, terminating the token with a null character. More tokens can be broken out of the remainder of strToken by a series of calls to strtok. Each call to strtok modifies strToken by inserting a null character after the token returned by that call. To read the next token from strToken, call strtok with a NULL value for the strToken argument. The NULL strToken argument causes strtok to search for the next token in the modified strToken. The strDelimit argument can take any value from one call to the next so that the set of delimiters may vary.

        Warning Each of these functions uses a static variable for parsing the string into tokens. If multiple or simultaneous calls are made to the same function, a high potential for data corruption and inaccurate results exists. Therefore, do not attempt to call the same function simultaneously for different strings and be aware of calling one of these function from within a loop where another routine may be called that uses the same function. However, calling this function simultaneously from multiple threads does not have undesirable effects.

        Example

        /* STRTOK.C: In this program, a loop uses strtok
        * to print all the tokens (separated by commas
        * or blanks) in the string named "string".
        */

        #include <string.h>
        #include <stdio.h>

        char string[] = "A string\tof ,,tokens\nand some more tokens";
        char seps[] = " ,\t\n";
        char *token;

        void main( void )
        {
        printf( "%s\n\nTokens:\n", string );
        /* Establish string and get the first token: */
        token = strtok( string, seps );
        while( token != NULL )
        {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
        }
        }

        Comment

        • FeelTheRT
          Registered User
          • Jun 2001
          • 2950

          #5
          when would u void main?
          FS: RARE Adrenaline Angel LED #8



          ~~~ FS:ASA, angled drop ~~~
          ~~~ FS: DYE sight rail && Angel LCD bolt

          Comment

          • dave_p

            #6
            not really sure what you are asking.

            void main(void)
            {

            }
            you void main when you dont wish for main to return a value, if thats what you are getting at.
            as opposed to :

            int main(void)
            {
            return 0;
            }
            when you wish to return a value, for say error checking or exit codes. for the most part all my unix C/C++ books are keen on main() returning a value whereas DOS/windows tutorials seem to return void alot of the time for some reason. for trivial code i always return void.

            Comment

            • dave_p

              #7
              the void in the () means you dont want to pass in any values to main as well,
              its not necessary, you can leave it empty i.e: main(). i do either depending on my mood. when i code C i use the void main(void) style, for C++ i use void main().

              if thats what you meant.

              Comment

              • FeelTheRT
                Registered User
                • Jun 2001
                • 2950

                #8
                kinda what i ment... i know very little about C++, all i do is int main() all the time, i don't understand when you would void main()
                FS: RARE Adrenaline Angel LED #8



                ~~~ FS:ASA, angled drop ~~~
                ~~~ FS: DYE sight rail && Angel LCD bolt

                Comment

                • Miscue
                  Super Moderator

                  • Oct 2000
                  • 7105

                  #9
                  Using strtok() in this situation is goofy.
                  strtok is VERY useful when you have complex delimiters or do not know how much stuff is going to be in between the delimiters... like when you're executing stuff with system calls and you got to separate command line arguments and stuff... but in this case you know exactly what it will be... MM/DD/YYYY or whatever.

                  Even if you used strtok, you would still have to make a second pass to convert the chopped up strings into ints... unneccessary extra steps.

                  Just read in each number, and ignore the '/'s... !!!

                  Easy!

                  There's probably an easier way to do this but you can go about it this way:


                  /**********************************************/
                  int month=0; // Initialize
                  int day=0;
                  int year=0;

                  char temp;

                  cin.get(temp); // Gets next char from input & is priming read
                  while (temp != '/') // While hasn't reached '/'
                  {
                  month *= 10; // Shifts left, See <B>*note</B>
                  month += int(temp - '0'); // Add next digit. (temp - '0' is to convert a char to an int.)
                  cin.get(temp); // Get next char
                  }

                  cin.get(temp); // Priming Read
                  while(temp != '/')
                  {
                  day *= 10;
                  day += int(temp - '0');
                  cin.get(temp);
                  }

                  cin.get(temp);
                  while(temp != '\n')
                  {
                  year *= 10;
                  year += int(temp - '0');
                  cin.get(temp);
                  }

                  /********************************************/

                  <B>*Note:</B> Say you were to read in '12'. First you read '1'. You shift left so now you have 10. Then, you read in the 2 and add to the 10... you get 12.



                  Now, I didn't try running this so dunno if it's perfect. But you can see what I'm doing here and figure it out. There's a ton of different ways you can go about this problem... I figure that you're still learning right now... and this you should be able to understand. Strtok is a bit more than what you need to know at this point... and really isn't a 'better' way of doing things in this situation. It's not that it's 'hard'... because it's not... but good to take baby steps if you know what I mean.

                  Maybe your instructor will let you use MM / DD / YY putting spaces in between... that would simplify things. Or if not, I think there's a way to make an arbitrary char the delimiter for cin... instead of white space. That would be a VERY easy way of doing it. A cin >> month >> day >> year; ... using '/' as your delimiter would make it REALLY easy! But you can look it up if you are curious - looking things up is part of the learning experience after all...
                  Last edited by Miscue; 03-24-2002, 12:47 PM.

                  Comment

                  • dave_p

                    #10
                    the beauty of C++ is that you can do the same thing many ways.

                    miscues implementation is more tailored to the task where mine used a general purpose function.

                    but miscue you are still making a conversion to int. setting the cin delimiter would be the slickest solution though.

                    cin.get() has an overloaded form that takes a delimiter, here is the section from the from the MSDN:

                    istream::get
                    int get();&

                    istream& get( char* pch, int nCount, char delim = '\n' );

                    istream& get( unsigned char* puch, int nCount, char delim = '\n' );

                    istream& get( signed char* psch, int nCount, char delim = '\n' );

                    istream& get( char& rch );

                    istream& get( unsigned char& ruch );

                    istream& get( signed char& rsch );

                    istream& get( streambuf& rsb, char delim = '\n' );

                    Parameters

                    pch, puch, psch

                    A pointer to a character array.

                    nCount

                    The maximum number of characters to store, including the terminating NULL.

                    delim

                    The delimiter character (defaults to newline).

                    rch, ruch, rsch

                    A reference to a character.

                    rsb

                    A reference to an object of a streambuf-derived class.

                    Remarks

                    These functions extract data from an input stream as follows:

                    Variation Description
                    get(); Extracts a single character from the stream and returns it.
                    get( char*, int, char ); Extracts characters from the stream until either delim is found, the limit nCount is reached, or the end of file is reached. The characters are stored in the array followed by a null terminator.
                    get( char& ); Extracts a single character from the stream and stores it as specified by the reference argument.
                    get( streambuf&, char ); Gets characters from the stream and stores them in a streambuf object until the delimiter is found or the end of the file is reached. The ios::failbit flag is set if the streambuf output operation fails.


                    In all cases, the delimiter is neither extracted from the stream nor returned by the function. The getline function, in contrast, extracts but does not store the delimiter.

                    sorry gimp i know you asked a simple question, now you got miscue and i on a roll. like miscue said, find something simple that works.
                    Last edited by Guest; 03-24-2002, 03:56 PM.

                    Comment

                    • Miscue
                      Super Moderator

                      • Oct 2000
                      • 7105

                      #11
                      Coolness... yep, that's a good way to do it!

                      Comment

                      • gimp
                        Registered User
                        • Jan 2001
                        • 2368

                        #12
                        well, this is what I did, it worked fine. All that stuff is to complicated for the simple programs in Comp Sci 2.

                        char temp;
                        int day, month, year;
                        cin >> month >> temp >> day >> temp >> year;

                        Comment

                        • Miscue
                          Super Moderator

                          • Oct 2000
                          • 7105

                          #13
                          /me throws rock at Gimp. Hahaha. Well, good to see that you have it figured out.

                          Comment

                          Working...