Menu

#17 strings not working in a 'printf' command

closed-invalid
5
2007-12-14
2007-12-10
No

It seems that the susbtitution of strings is not working in 'printf' commands. In the script below, the first loop does not use the string @varname so the printf command works ok, but the second loop uses that string and gretl gives an error.

<script>
nulldata 50
genr x = normal()
string varname = "x"
loop for i=1..50 --quiet
scalar ti=i
printf "%s\t %10.0f\n", date(ti), x[i]
endloop

loop for i=1..50 --quiet
scalar ti=i
printf "%s\t %10.0f\n", date(ti), @varname[i]
endloop
</script>

Discussion

  • Riccardo "Jack" Lucchetti

    Logged In: YES
    user_id=1368575
    Originator: NO

    This is due to the fact that in a (s)printf statement string substitution ended with the format line; I think this was meant to optimise things. The following patch fixes it: Allin, please check I haven't overlooked something.

    Index: lib/src/gretl_string_table.c

    RCS file: /cvsroot/gretl/gretl/lib/src/gretl_string_table.c,v
    retrieving revision 1.36
    diff -u -r1.36 gretl_string_table.c
    --- lib/src/gretl_string_table.c 14 Nov 2007 22:44:52 -0000 1.36
    +++ lib/src/gretl_string_table.c 11 Dec 2007 20:29:10 -0000
    @@ -992,10 +992,6 @@

    while (*s && !err) {
    if (pf) {
    - if (*s == '"' && (bs % 2 == 0)) {
    - /* reached end of format string: stop substituting */
    - break;
    - }
    if (*s == '\\') {
    bs++;
    } else {

     
  • Allin Cottrell

    Allin Cottrell - 2007-12-13
    • assigned_to: nobody --> allin
     
  • Allin Cottrell

    Allin Cottrell - 2007-12-13

    Logged In: YES
    user_id=330339
    Originator: NO

    It is by design that string substitution does not operate for the
    _arguments_ to (s)printf: in that context @xxx string variables are
    treated as variables, not macros. See section 11.2 of the User's
    Guide.

    The proposed patch would break this sort of usage:

    string foo = "avocado"
    printd "foo = %s\n", @avocado

     
  • Nobody/Anonymous

    Logged In: NO

    I see. I hadn't thought of this.

    Besides, the problem is easy to circumvent by assigning the value to be printed to a temporary scalar, eg

    <script>
    loop for i=1..50 --quiet
    scalar ti=i
    scalar tmp = @varname[i]
    printf "%s\t %10.0f\n", date(ti), x
    endloop
    </script>

    I guess this bug can be closed, then.

     
  • Allin Cottrell

    Allin Cottrell - 2007-12-14
    • status: open --> closed-invalid
     

Log in to post a comment.