Thread: Multiple variables in sprintf

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    62

    Multiple variables in sprintf

    I need to do the following

    sprintf (x, "pgrep -u %s | sed %i 'q;d', y,z);

    but it doesn't seem to work. Is this possible with sprintf? If so it must be some other issue in my code.

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    You only have one " character, where is your format string supposed to end?

    Code:
    #include <stdio.h>
    int main(void)
    {
        char x[256];
        char y[] = "foo";
        int z = 3;
        sprintf (x, "pgrep -u %s | sed %i 'q;d'", y,z);
        puts(x);
    }
    /* my output:
    pgrep -u foo | sed 3 'q;d'
    */
    Last edited by cwr; 02-15-2006 at 09:14 PM.

  3. #3
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Your syntax is all screwed up there, I'm not even sure what you're trying to do. You realize you're never closing your double quotes?

    Edit: cwr beat me, which is great cause I'm going to sleep anyway.
    Sent from my iPadŽ

  4. #4
    Registered User
    Join Date
    Jan 2006
    Posts
    62
    Quote Originally Posted by cwr
    You only have one " character, where is your format string supposed to end?

    Code:
    #include <stdio.h>
    int main(void)
    {
        char x[256];
        char y[] = "foo";
        int z = 3;
        sprintf (x, "pgrep -u %s | sed %i 'q;d'", y,z);
        puts(x);
    }
    /* my output:
    pgrep -u foo | sed 3 'q;d'
    */
    Yes that's precisely what I'm trying to do. Would this be better?
    [code]
    sprintf (x, "pgrep -u %s | sed %i \'q;d\'", y,z);
    [code\]

  5. #5
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    You don't need to escape the ' characters. Does my example produce the result you desire?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. why Multiple define error ...
    By nilathinesh in forum C Programming
    Replies: 2
    Last Post: 10-19-2006, 06:31 AM
  2. Declaring an variable number of variables
    By Decrypt in forum C++ Programming
    Replies: 8
    Last Post: 02-27-2005, 04:46 PM
  3. Headers and Global Variables
    By ajoo in forum C++ Programming
    Replies: 1
    Last Post: 05-15-2004, 04:49 AM
  4. Replies: 6
    Last Post: 01-02-2004, 01:01 PM
  5. Replies: 1
    Last Post: 05-01-2003, 02:52 PM