separator in scanf

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • giacomomarciani
    New Member
    • Jan 2012
    • 4

    separator in scanf

    How can I let a scanf recognize some separators?
    For example:
    user input a stream via scanf:
    Giacomo Marciani,male,2 7/06/1990

    The program should recognize "," and "/" as separators, and assign Giacomo to a char*, Marciani to another char*,male to another char*,27 to a int,06 to another int and 1990 to another int.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I would just read the entire sequence in as a sring and parse it out afterwards maybe using strtok.

    Comment

    • giacomomarciani
      New Member
      • Jan 2012
      • 4

      #3
      isn't possible to use a simple scanf? :-)

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        scanf has an argument that is a char* where you supply your format string. This string uses % to identify a formst type. %d will fetch bytes until it encounters one that can't be part of an int. There's no notion of a delimiter with this function.

        If you scanf into a string and call strtok you can specify your own delimiters. strtok will return the characters up to the delimiter as a token in the form of a string. You then strcpy this token into your desired variable.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          According the documentation, the %s conversion specifier in scanf recognizes whitespace as a separator. If that's true, then you could read an input string of this sort:
          Giacomo Marciani male 27/06/1990
          with
          Code:
          char firstName[80];
          char lastName[80];
          char gender[80];
          int day, month, year;
          ...
          scanf("%s%s%s%d/%d/%d",
              firstName, lastName, gender, &day, &month, &year);
          Take this advice with a grain of salt ... I never use scanf in my own software.

          Comment

          Working...