Search code examples
printfformat-specifiers

Format-Specifiers Syntax Error?


i am having a little trouble with printf specifiers...so before asking you guys i read almost everything onC++Reference page, but couldnt fix the problem, and since i am new at c i cant even understand the problem, its most likely a syntax error but i can't find it...

for(i = 1; i <= 10; i++) {  
    printf("\n%d.%s%n",i,names[i-1],offset);
    printf("%*s%.2f TL",10-offset," ",prices[i-1]);
}

so basically i have this code to print a list, and i want the prices to start from the same column. For e.g:

  1. water 1.00
  2. oj 1.00

and the logic behind my code (incase it's not obvious, i can't tell if it is) is:

  • print id number and name, count how many chars we've written so far and assign it to offset.
  • print (starting column of price list)-offset spaces before price

once i couldn't get the result i want, i checked and found out that offset is 3 for all names which is not the case(and no value is assigned to offset before this procedure).

Thanks for any kind of help !

PS: This is a practice code just to get better at using specifiers efficiently.

edit: so i did this :

for(i=1;i<=10;i++)

{

printf("%d.%s%n",i,names[i-1],&offset);
printf("%*s%.2f TL\n",10-offset," ",prices[i-1]);

}

but what i get as a result is huge empty black command screen.


Solution

  • The %n format specifier requires a pointer. Your code is missing the & operator for offset:

    printf("\n%d.%s%n",i,names[i-1],&offset);
    

    The good ol' C interface doesn't know what types you supply to printf so it doesn't complain and happily reads the 4 byte integer value of offset on the stack as a memory location -> core dump.

    Actually, g++ with -Wall does warn. So

    • hd1 has a point here because C++ output is type safe (even though it's a pain);
    • Heed thy warnings.