SSCANF

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Superfox il Volpone

    #1

    SSCANF

    Hello

    I have some problem with sscanf, I tryed this code but it doesn't works
    :

    char* stringa = "18/2005"
    char mese[3]; char anno[5];
    int i_letture;

    i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);
    mese[2] = anno[4] = '\0';

    The values ar random and I don't understand the motive
    I tryed either this variant :

    char* porka_vakka = strchr(stringa, '/');
    *porka_vakka = '\0'; // but either ' ' e '\n'
    i_letture = sscanf(stringa, "%s", &mese);

    But neither this works...

    Could anyone help me ?

    Bye
    - Atari

    p.s. happy new year :)

  • nelu

    #2
    Re: SSCANF


    Superfox il Volpone wrote:[color=blue]
    > Hello
    >
    > I have some problem with sscanf, I tryed this code but it doesn't works
    > :
    >
    > char* stringa = "18/2005"
    > char mese[3]; char anno[5];
    > int i_letture;
    >
    > i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);
    > mese[2] = anno[4] = '\0';[/color]

    You have mese[3] and anno[5]. When you read with sscanf you tell it to
    store the character arrays in &mese and &anno. mese=&mese[0] and
    anno=&anno[0].
    It should be: i_letture=sscan f(stringa,"%2s/%4s",mese,anno) , otherwise
    you are trying to write those values at locations that hold the
    addresses of mese and anno instead of writing them to the addresses
    where mese and anno point.
    If you really want to use & then write:
    i_letture=sscan f(stringa,"%2s/%4s",&mese[0],&anno[0]);
    [color=blue]
    >
    > The values ar random and I don't understand the motive
    > I tryed either this variant :
    >
    > char* porka_vakka = strchr(stringa, '/');
    > *porka_vakka = '\0'; // but either ' ' e '\n'
    > i_letture = sscanf(stringa, "%s", &mese);[/color]
    Same problem as above. Reading into the wrong location.

    Comment

    • Mike Wahler

      #3
      Re: SSCANF

      "Superfox il Volpone" <atari@email.it > wrote in message
      news:1136310085 .816491.322760@ g14g2000cwa.goo glegroups.com.. .[color=blue]
      > Hello
      >
      > I have some problem with sscanf, I tryed this code but it doesn't works
      > :
      >
      > char* stringa = "18/2005"[/color]

      "18/2005" is a string literal. Any attempts to modify
      any of its characters produces undefined behavior.
      [color=blue]
      > char mese[3]; char anno[5];
      > int i_letture;
      >
      > i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);[/color]

      This gives undefined behavior. You're trying to modify
      a string literal.

      Also, since 'mese' and 'anno' are arrays, their names
      in this context will evalutate to pointers to their
      first element. So e.g. use 'mese', not '&mese'.
      %s must match with type 'char*'. The expression &mese
      does not have that type. Its type is (*)[3] (pointer to
      array of three char). Not the correct type.
      [color=blue]
      > mese[2] = anno[4] = '\0';[/color]

      'sscanf()' already applies the string terminator for you
      (in the proper location)

      Also (disregarding for now the string literal problem)
      note that if the size of data stored by 'sscanf()' is
      less than the size of the array, your arbitrary placement of
      '\0' as the last array element will not terminate the string
      properly (there will be 'garbage' between the data and the
      terminator).
      [color=blue]
      >
      > The values ar random and I don't understand the motive[/color]

      You don't understand how 'sscanf()' works, or how arrays
      and pointers work.
      [color=blue]
      > I tryed either this variant :
      >
      > char* porka_vakka = strchr(stringa, '/');
      > *porka_vakka = '\0'; // but either ' ' e '\n'[/color]

      There are two possible results of these two lines, both of
      which are undefined behavior:

      1) The character '/' is not found in the string (which
      causes 'strchr()' to return NULL), in which case you
      try to dereference a NULL pointer. Undefined behavior.

      2) The character '/' is found (and 'strchr()' returns its
      address. You then try to modify it, but it's part of
      a string literal. Undefined behavior.
      [color=blue]
      > i_letture = sscanf(stringa, "%s", &mese);[/color]

      More undefined behavior. Attemt to modify string literal.
      Wrong data type used with '%s'.

      Finally, even if you do have writable storage for 'sscanf()'
      note that you have no protection against the data overflowing
      your array. Look up the 'width' flag for sscanf() format
      specifiers.
      [color=blue]
      >
      > But neither this works...
      >
      > Could anyone help me ?[/color]

      I think the best advice I can give is to recommend you get
      some good textbooks.


      -Mike


      Comment

      • Michael Mair

        #4
        Re: SSCANF

        Mike Wahler wrote:[color=blue]
        > "Superfox il Volpone" <atari@email.it > wrote in message
        > news:1136310085 .816491.322760@ g14g2000cwa.goo glegroups.com.. .
        >[color=green]
        >>Hello
        >>
        >>I have some problem with sscanf, I tryed this code but it doesn't works
        >>:
        >>
        >>char* stringa = "18/2005"[/color]
        >
        > "18/2005" is a string literal. Any attempts to modify
        > any of its characters produces undefined behavior.
        >[color=green]
        >>char mese[3]; char anno[5];
        >>int i_letture;
        >>
        >>i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);[/color]
        >
        > This gives undefined behavior. You're trying to modify
        > a string literal.[/color]

        Look again.
        The first parameter of sscanf() is of type const char *
        (qualified by restrict in C99 IIRC).

        I guess you saw sscanf() and thought sprintf()...

        <snip>


        Cheers
        Michael
        --
        E-Mail: Mine is an /at/ gmx /dot/ de address.

        Comment

        • Christopher Benson-Manica

          #5
          Re: SSCANF

          Mike Wahler <mkwahler@mkwah ler.net> wrote:
          [color=blue][color=green]
          > > i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);[/color][/color]
          [color=blue]
          > This gives undefined behavior. You're trying to modify
          > a string literal.[/color]

          I don't know that OP is "trying" to modify the string literal. In
          practice, is sscanf() really likely to modify its first argument?

          --
          Christopher Benson-Manica | I *should* know what I'm talking about - if I
          ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

          Comment

          • Chris McDonald

            #6
            Re: SSCANF

            Christopher Benson-Manica <ataru@nospam.c yberspace.org> writes:
            [color=blue]
            >Mike Wahler <mkwahler@mkwah ler.net> wrote:[/color]
            [color=blue][color=green][color=darkred]
            >> > i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);[/color][/color][/color]
            [color=blue][color=green]
            >> This gives undefined behavior. You're trying to modify
            >> a string literal.[/color][/color]
            [color=blue]
            >I don't know that OP is "trying" to modify the string literal. In
            >practice, is sscanf() really likely to modify its first argument?[/color]


            Doesn't the prototype of sscanf() promise to *not* modify its first argument?

            --
            Chris.

            Comment

            • Emmanuel Delahaye

              #7
              Re: SSCANF

              Superfox il Volpone a écrit :[color=blue]
              > I have some problem with sscanf, I tryed this code but it doesn't works
              > :
              >
              > char* stringa = "18/2005"
              > char mese[3]; char anno[5];[/color]

              These are arrays of char
              [color=blue]
              > int i_letture;
              >
              > i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);[/color]

              why & ? %s expects exactly what the name of an array of char is : the
              address of its first element.

              The separator must be read too :

              #include <stdio.h>

              int main(void)
              {
              char* stringa = "18/2005";
              char mese[3];
              char anno[5];
              char c;
              int i_letture = sscanf(stringa, "%2s%c%4s", mese, &c, anno);

              if (i_letture == 3)
              {
              printf ("'%s' '%s'\n", mese, anno);
              }
              else
              {
              printf ("sscanf() error\n");
              }
              return 0;
              }
              [color=blue]
              > mese[2] = anno[4] = '\0';[/color]

              No need for that.

              --
              A+

              Emmanuel Delahaye

              Comment

              • Mike Wahler

                #8
                Re: SSCANF


                "Michael Mair" <Michael.Mair@i nvalid.invalid> wrote in message
                news:4202kbF1gg ba5U1@individua l.net...[color=blue]
                > Mike Wahler wrote:[color=green]
                >> "Superfox il Volpone" <atari@email.it > wrote in message
                >> news:1136310085 .816491.322760@ g14g2000cwa.goo glegroups.com.. .
                >>[color=darkred]
                >>>Hello
                >>>
                >>>I have some problem with sscanf, I tryed this code but it doesn't works
                >>>:
                >>>
                >>>char* stringa = "18/2005"[/color]
                >>
                >> "18/2005" is a string literal. Any attempts to modify
                >> any of its characters produces undefined behavior.
                >>[color=darkred]
                >>>char mese[3]; char anno[5];
                >>>int i_letture;
                >>>
                >>>i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);[/color]
                >>
                >> This gives undefined behavior. You're trying to modify
                >> a string literal.[/color]
                >
                > Look again.
                > The first parameter of sscanf() is of type const char *
                > (qualified by restrict in C99 IIRC).
                >
                > I guess you saw sscanf() and thought sprintf()...[/color]

                Um, yes. Oops. Blush. Sorry. Er, Happy New Year and all that. :-)

                -Mike


                Comment

                • Emmanuel Delahaye

                  #9
                  Re: SSCANF

                  Mike Wahler a écrit :[color=blue][color=green]
                  >>char* stringa = "18/2005"[/color]
                  >
                  > "18/2005" is a string literal. Any attempts to modify
                  > any of its characters produces undefined behavior.[/color]

                  How would it be modified ? I'm curious. Isn't the first parameter of
                  sscanf() a char const * ?

                  --
                  A+

                  Emmanuel Delahaye

                  Comment

                  • Robert Harris

                    #10
                    Re: SSCANF

                    Superfox il Volpone wrote:[color=blue]
                    > Hello
                    >
                    > I have some problem with sscanf, I tryed this code but it doesn't works
                    > :
                    >
                    > char* stringa = "18/2005"[/color]
                    Missing ';' termination[color=blue]
                    > char mese[3]; char anno[5];
                    > int i_letture;
                    >
                    > i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);
                    > mese[2] = anno[4] = '\0';[/color]
                    Unnecessary here: sscanf NUL-terminates the results[color=blue]
                    >
                    > The values ar random and I don't understand the motive[/color]

                    Well, it works for me! What makes you think the result is wrong?

                    Robert

                    Comment

                    • Mike Wahler

                      #11
                      Re: SSCANF


                      "Emmanuel Delahaye" <emdel@YOURBRAn oos.fr> wrote in message
                      news:43bae22d$0 $15331$79c14f64 @nan-newsreader-07.noos.net...[color=blue]
                      > Mike Wahler a écrit :[color=green][color=darkred]
                      >>>char* stringa = "18/2005"[/color]
                      >>
                      >> "18/2005" is a string literal. Any attempts to modify
                      >> any of its characters produces undefined behavior.[/color]
                      >
                      > How would it be modified ? I'm curious. Isn't the first parameter of
                      > sscanf() a char const * ?[/color]

                      Brain malfunction. Read 'sscanf', saw 'sprintf'.
                      My apologies.

                      -Mike


                      Comment

                      • Superfox il Volpone

                        #12
                        Re: SSCANF

                        Sorry people, what I posted it's part of a more large program and the
                        printf with I verified it was wrong :)

                        I solved but I don't understand one thing :
                        the sscanf works with '&mese' and 'mese' in the correct manner : maybe
                        it's the compiler (GCC) that does some correction ?

                        The second thing if I want to jump one argument is it correct the
                        behaviour ?
                        year[5]
                        sscanf(str_date , "%*s/%4s", year);

                        and at last, at year will be placed the string terminator ('\0')

                        Bye & thx all for the help
                        ~ Superfox il Volpone :)

                        Comment

                        • Keith Thompson

                          #13
                          Re: SSCANF

                          "Superfox il Volpone" <atari@email.it > writes:[color=blue]
                          > Sorry people, what I posted it's part of a more large program and the
                          > printf with I verified it was wrong :)[/color]

                          For context, here's the code you posted:

                          char* stringa = "18/2005"
                          char mese[3]; char anno[5];
                          int i_letture;

                          i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);
                          mese[2] = anno[4] = '\0';

                          Please read <http://cfaj.freeshell. org/google/>.

                          This also demonstrates why you should always post a small, complete,
                          compilable program. We can't guess whether the part you didn't post
                          is what's causing the problem (in this case, it was). What you posted
                          wasn't even a correct code fragment; the declaration of stringa is
                          missing a semicolon, an error that the compiler would have caught.
                          Don't try to re-type your code; copy-and-paste *exactly* what you fed
                          to the compiler.
                          [color=blue]
                          > I solved but I don't understand one thing :
                          > the sscanf works with '&mese' and 'mese' in the correct manner : maybe
                          > it's the compiler (GCC) that does some correction ?[/color]

                          Given, for example,

                          char anno[5];

                          the expression "anno", an array name, is implicitly converted (in most
                          contexts) to a pointer to the array's first element; in this case, the
                          resulting expression is of type char*. The expression "&anno" yields
                          the address of the array; the resulting expression is of type
                          char (*p)[5], i.e., a pointer to an array of 5 chars.

                          These two expressions are of different types, but they're both
                          pointers, they both (in some sense) have the same value, and they
                          *probably* both have the same representation.

                          Since sscanf() takes a variable number and type(s) of arguments, the
                          compiler doesn't know what types are expected for the third and fourth
                          arguments in your call; it just blindly passes in whatever you
                          specify. It's your job to make sure you call it correctly. Since the
                          arguments you gave it were (probably) the same size and representation
                          as the correct arguments, it happened to work. (Passing something of
                          an incorrect type to sscanf() actually invokes undefined behavior;
                          working "correctly" is one of the many possible consequences.)

                          BTW, I believe there are real systems where char* and char (*p)5 would
                          have different representations , and your sscanf() call would fail.
                          [color=blue]
                          > The second thing if I want to jump one argument is it correct the
                          > behaviour ?
                          > year[5]
                          > sscanf(str_date , "%*s/%4s", year);
                          >
                          > and at last, at year will be placed the string terminator ('\0')[/color]

                          Yes, that should work (assuming the declaration is "char year[5]"
                          rather than "year[5]").

                          --
                          Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                          San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                          We must do something. This is something. Therefore, we must do this.

                          Comment

                          • Christopher Benson-Manica

                            #14
                            Re: SSCANF

                            Chris McDonald <chris@csse.uwa .edu.au> wrote:
                            [color=blue]
                            > Doesn't the prototype of sscanf() promise to *not* modify its first argument?[/color]

                            I would have sworn that my K&R2 at work gave the type of sscanf()'s
                            first argument as char*, but I see from n869 that either I or K&R2 am
                            mistaken. Apologies. It still begs the question of how it can modify
                            a string literal, however.

                            --
                            Christopher Benson-Manica | I *should* know what I'm talking about - if I
                            ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

                            Comment

                            • Richard Heathfield

                              #15
                              Re: SSCANF

                              Christopher Benson-Manica said:
                              [color=blue]
                              > Chris McDonald <chris@csse.uwa .edu.au> wrote:
                              >[color=green]
                              >> Doesn't the prototype of sscanf() promise to *not* modify its first
                              >> argument?[/color]
                              >
                              > I would have sworn that my K&R2 at work gave the type of sscanf()'s
                              > first argument as char*,[/color]

                              It does. It's listed in the errata.
                              [color=blue]
                              > but I see from n869 that either I or K&R2 am
                              > mistaken. Apologies. It still begs the question of how it can modify
                              > a string literal, however.[/color]

                              No, it doesn't beg the question. "To beg the question" means "to assume as
                              an implicit premise something you are seeking to prove".

                              --
                              Richard Heathfield
                              "Usenet is a strange place" - dmr 29/7/1999

                              email: rjh at above domain (but drop the www, obviously)

                              Comment

                              Working...