Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sprintf string re-position

Status
Not open for further replies.

bearfish

Programmer
Nov 10, 2003
28
MY
I have a string consist of 25bytes concatenate together by 3 different string.
The first string consist max 8 bytes.
If the first string is less than 8 bytes, I want to position it to the right side. I use the command:
sprintf(tmpBuf, "%8.*s", sizeof(8), datapart1);
But when it printed out with all the 3 string, the result is:
"123 2012345 "
The result that I wanted it to be is:
" 1232012345 "
Does anyone know what is wrong with my sprintf statement?
Thank you.
 
Alas, all is (are?) wrong.
1. sizeof(8) == sizeof(int). Obviously, it's senseless using of * in format specification. Minus sign after % is a part of specification (flag). You can't construct conditional format with arg list only (via * or what else).
2. Default alignment is right. So use %8.8s for the 1st arg.
3. Use %-s (left alignment) for the 2nd and 3rd args (where is your code?).

So use a format like this (for all 3 args):
Code:
"%8.8s%-s%-s"
 
I've tried use "%8.8" before and the program traps.
The codes look like this..
sprintf(tmpBuf,"%8.8s",8,tbl.fld1);
strcat(dataBuf,tmpBuf);
sprintf(tmpBuf,"%s",2,tbl.fld2);
strcat(dataBuf,tmpBuf);
sprintf(tmpBuf,"%s",15,tbl.fld3);
any other suggestions? or why it traps?
 
Of course, the program crashed on this code(s):
Code:
sprintf(tmpBuf,"%s",2,tbl.fld2);
...
sprintf(tmpBuf,"%s",15,tbl.fld3);
The 2 (15 in the 2nd call) int const treated as a pointer to char (%s) - then you have a memory exception...
Read more about (s)printf() format/arguments relations (in any C book;)...

What for you have 3 calls with strcats instead of a clear and direct sprintf("%8.8s%-s%-s",..,..,..)?
 
ok. thanks.
for clarity purpose, everything shrink into one single statement will result in a very long statement.
 
> everything shrink into one single statement will result in a very long statement.
So put it on many lines
Code:
sprintf(tmpBuf,
        "%8.8s"
        " %s"
        " %s",
        tbl.fld1,
        tbl.fld2,
        tbl.fld3);

--
 
sorry for my flimsy code.
i reconstruct my line again for the part1 data,
sprintf(tmpBuf,"%8.8s",tbl.fld1);
but still the data when printed out aligned to the left eventhough I've added "%+8.8s", by default it is not necessary. Any idea why?
 
It's impossible if your string is shorter than a field width. May be you have trailing spaces in it?
Try to print test string with <8 characters (with %8.8s)...
Or change a wrong compiler (with non-standard library)...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top