Cas1337
Cas1337

Reputation: 141

Format a printed char array in C - quotations marks and right aligment

I'm new on C and I'm having troubles trying to format a String.

The format that I use to print is this:

cp = "42947295";
printf("String value: \"%-10s\"  <-->  Unsigned long value: %10lu\n", cp, dwAtoDW(cp));

cp = "123456789";
printf("String value: \"%-10s\"  <-->  Unsigned long value: %10lu\n", cp, dwAtoDW(cp));

cp = "100000";
printf("String value: \"%-10s\"  <-->  Unsigned long value: %10lu\n", cp, dwAtoDW(cp));

unsigned long dwAtoDW(char* cpPtr) {
    number = 0;
    while (*cpPtr) {
        if (*cpPtr >= '0' && *cpPtr <= '9') {
            number *= 10;
            number += *cpPtr - '0';
        } else {
            return 0;
        }
    *cpPtr++;
    }
    return number;
}

And I have the following output:

String value: "4294967295"    Unsigned long value: 4294967295
String value: " 123456789"    Unsigned long value:  123456789
String value: "    100000"    Unsigned long value:     100000

As you can see, when printing values that are less that 10 characters long, it prints spaces between the two quotations marks. What I want is to maintain the right alignment, with the quotation marks arround the whole number, like this:

String value: "4294967295"    Unsigned long value: 4294967295
String value:  "123456789"    Unsigned long value:  123456789
String value:     "100000"    Unsigned long value:     100000

Is there a way to do that with printf format codes?

Thanks.

Upvotes: 0

Views: 263

Answers (1)

R Sahu
R Sahu

Reputation: 206697

You cannot do this using one line of printf. However, you can use sprintf first to put the quotes around the text, and then use printf to align the output.

char buffer[20];
sprintf(buffer, "\"%s\"", tp);
printf("String value: %-12s  <-->  Unsigned long value: %10lu\n", buffer, dwAtoDW(cp));

Upvotes: 3

Related Questions