質問

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.

役に立ちましたか?

解決

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.

他のヒント

When you use %n in a printf format, the corresponding parameter must be a pointer. printf will store the information in the int you point it to.

Assuming you've declared int offset somewhere, you should use &offset as the last argument in your printf call.

While we're here, allow me to comment on this excerpt:

printf("\n

ARGH NO! Newline is a terminator. It goes at the end of a line, not the beginning.

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.

edit: Can you guys try this and tell me if you get normal results? I can't understand the mistake occuring, so i can't get past it...Maybe some other examples will lead me to where is the mistake.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top