473,796 Members | 2,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to left pad a string with spaces?

If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:

" This is a string";
Thanks!
Jun 27 '08
41 12470
Ben Bacarisse wrote:
"rio" <a@b.cwrites:

<lost of code snipped>
>this seems good
not know if compile

Despite the almost deliberate attempt to obscure the code I spotted
errors in all the versions you posted. Why not take a little more
time, think about the solution, and do some testing?
This guy is notorious for obscuring _all_ of his code, not just C. You
should look at his custom x86 assembler language is alt.lang.asm
sometime. No amount of argument over the years has seemed to convince
him of the benefits of legible code.

Jun 27 '08 #31
rio

"Ben Bacarisse" <be********@bsb .me.ukha scritto nel messaggio
news:87******** ****@bsb.me.uk. ..
"rio" <a@b.cwrites:

<lost of code snipped>
>this seems good
not know if compile

Despite the almost deliberate attempt to obscure the code I spotted
errors in all the versions you posted. Why not take a little more
time, think about the solution, and do some testing?
????
i miss all your post in my server news that correct myself
the only one that answe me that i see is this one above

have you not good news server? :)

anyway the last one should be correct if i add
if(d==0) goto l0;

--
Ben.


Jun 27 '08 #32
On Mon, 09 Jun 2008 18:57:04 -0400, nospam <no@spam.comwro te:
>If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:

" This is a string";
Thanks!
As long as your array is at least twice as long as (your string plus
the number of spaces to insert):
sprintf(myvar+6 4, "%s", myvar);
sprintf(myvar, " %s", myvar+64);
Remove del for email
Jun 27 '08 #33
rio

"rio" <a@b.cha scritto nel messaggio
news:48******** *************** @reader1.news.t in.it...
>
"Ben Bacarisse" <be********@bsb .me.ukha scritto nel messaggio
news:87******** ****@bsb.me.uk. ..
>"rio" <a@b.cwrites:

<lost of code snipped>
>>this seems good
not know if compile

Despite the almost deliberate attempt to obscure the code I spotted
errors in all the versions you posted. Why not take a little more
time, think about the solution, and do some testing?
I have not the C compiler here under my hands
so i write code without testing
????
i miss all your post in my server news that correct myself
the only one that answe me that i see is this one above

have you not good news server? :)

anyway the last one should be correct if i add
if(d==0) goto l0;
better if(d==0) return 0;

Don't you like my last creation? it will be not much fast

/*
d should be mallocched or 0
e.g.
char *d=0;
unsigned sz=0;
----
if((sz=the4spac es(&d, sz, string))==0) error();
free(*d);
----------
*/
%define SPAZI 4

unsigned the4spaces(char ** d, unsigned sz, char* s)
{char *p1, *p2, p;
unsigned c, r;
/*************** *****/
if(d==0||SPAZI< 0) return 0;
if(s==0) goto l0;
if( (int) (c=strlen(s)) < 0) goto l0;
r=sz; p=*d;
if(c+SPAZI +1<sz)
{if( (p=realloc(*d, c+8))==0 )
{l0:; free(*d); *d=0; return 0;}
r=c+8; *d=p;}
p1=s; p2=p;
while( *p1 && (*p1==' '||*p1=='\t')) ++p1;
for(c=0; c<SPAZI ; ++c, ++p2) *p2=' '
while(*p2++=*p1 ++);
return r;}


Jun 27 '08 #34
rio

"rio" <a@b.cha scritto nel messaggio
news:48******** *************** @reader4.news.t in.it...
>"Ben Bacarisse" <be********@bsb .me.ukha scritto nel messaggio
news:87******* *****@bsb.me.uk ...
>>"rio" <a@b.cwrites:
So how many errors do you see?
[whithout use the compiler and with the use of the compiler]
/*
d should be mallocched or 0
e.g.
char *d=0;
unsigned sz=0;
----
if((sz=the4spac es(&d, sz, string))==0) error();
free(*d);
----------
*/
%define SPAZI 4

unsigned the4spaces(char ** d, unsigned sz, char* s)
{char *p1, *p2, p;
unsigned c, r;
/*************** *****/
if(d==0||SPAZI< 0) return 0;
if(s==0) goto l0;
if( (int) (c=strlen(s)) < 0) goto l0;
r=sz; p=*d;
if(c+SPAZI +1<sz)
{if( (p=realloc(*d, c+ SPAZI+8))==0 )
{l0:; free(*d); *d=0; return 0;}
r=c+ SPAZI +8; *d=p;}
p1=s; p2=p;
while( *p1 && (*p1==' '||*p1=='\t')) ++p1;
for(c=0; c<SPAZI ; ++c, ++p2) *p2=' '
while(*p2++=*p1 ++);
return r;}


Jun 27 '08 #35
Barry Schwarz <sc******@dqel. comwrites:
On Mon, 09 Jun 2008 18:57:04 -0400, nospam <no@spam.comwro te:
>>If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:

" This is a string";

As long as your array is at least twice as long as (your string plus
the number of spaces to insert):
sprintf(myvar+6 4, "%s", myvar);
sprintf(myvar, " %s", myvar+64);
I don't think that is permitted:

7.19.6.6 The sprintf function

... If copying takes place between objects that overlap, the
behavior is undefined.

It does not say "between /regions/ of objects that overlap". It seems
any overlap is enough to render it undefined.

--
Ben.
Jun 27 '08 #36
rio wrote:
"rio" <a@b.cha scritto nel messaggio
news:48******** *************** @reader4.news.t in.it...
>>"Ben Bacarisse" <be********@bsb .me.ukha scritto nel messaggio
news:87****** ******@bsb.me.u k...
"rio" <a@b.cwrites:

So how many errors do you see?
[whithout use the compiler and with the use of the compiler]
That's the problem with code and coding style: without running it thru a
compiler it is next to impossibe to detect the bugs.
Your code is just not writte for human consumption, and even you have
problems with it, hence the multiple versions you post to correct yourself.

Bye, Jojo
Jun 27 '08 #37
Ben Bacarisse wrote:
CBFalconer <cb********@yah oo.comwrites:
>Ben Bacarisse wrote:
>>CBFalconer <cb********@yah oo.comwrites:
... snip ...
>>>
void sstretch(char *s, int amount) {
char *p1, *p2;

if (amount) {
pi = strchr(s, '\0');
if ((p1 s) && amount) {
p2 = p1 + amount;
do { /* move the string */
*p2-- = *p1--;
} while {p1 s);
}
while (amount) { /* inject the blanks */
*s++ = ' ';
amount--;
}
}
} /* untested */

Yuck. Two typos and two logic errors. You complain about not
posting corrections, so the correction is:
.... snip ...
>>
One does it for the exercise.

But if you don't test it (or think about it enough) you get only the
illusion of exercising your C brain whereas, in fact, you are just
putting on "bug flab".
>I see only one typo [while {p1 s)]] and one unnecessary test
[&& amount]. A compilation may well show up more. What did you see?

pi in place of p1. The two logic bugs are:

(1) the loop does not run to the end -- you leave an un-copied
character. Note that this is slightly trick to correct.

(2) when the original string is empty (and amount 0) you just
write spaces over the null.
More than I expected. I guess I am getting sloppy. Well, I did
mark it 'untested', and say 'something like this'. :-)

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #38
On Tue, 10 Jun 2008 19:27:31 +0100, Ben Bacarisse
<be********@bsb .me.ukwrote:
>Barry Schwarz <sc******@dqel. comwrites:
>On Mon, 09 Jun 2008 18:57:04 -0400, nospam <no@spam.comwro te:
>>>If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:

" This is a string";

As long as your array is at least twice as long as (your string plus
the number of spaces to insert):
sprintf(myvar+6 4, "%s", myvar);
sprintf(myvar, " %s", myvar+64);

I don't think that is permitted:

7.19.6.6 The sprintf function

... If copying takes place between objects that overlap, the
behavior is undefined.

It does not say "between /regions/ of objects that overlap". It seems
any overlap is enough to render it undefined.
It seems that the term "object" is not used with great precision here.

What would happen if myvar were defined as
char myvar[2][64] = {"This ..."};
and in the calls to sprintf each use of myvar was cast to char*?
myvar[0] and [1] are objects that do not overlap but both are part of
the object myvar. Is this overlap? Would it be overlap if the
arguments were changed to myvar[0] and myvar[1]?

What about
char *myvar = malloc(128);
strcpy(myvar, "This ...");
There are no objects here so no objects can overlap.

The compiler will probably generate the same code for the three sets
of calls to sprintf. It doesn't seem right (tm) that the same code
generated from essentially identical source statements should be
undefined, questionable, and well defined, respectively.

I will assert that the intent of the word object in this section is
meant to refer to the source and destination strings and therefore
under the conditions I postulated there is no overlap.
Remove del for email
Jun 27 '08 #39
Barry Schwarz <sc******@dqel. comwrites:
On Tue, 10 Jun 2008 19:27:31 +0100, Ben Bacarisse
<be********@bsb .me.ukwrote:
>>Barry Schwarz <sc******@dqel. comwrites:
>>On Mon, 09 Jun 2008 18:57:04 -0400, nospam <no@spam.comwro te:

If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:

" This is a string";

As long as your array is at least twice as long as (your string plus
the number of spaces to insert):
sprintf(myvar+6 4, "%s", myvar);
sprintf(myvar, " %s", myvar+64);

I don't think that is permitted:

7.19.6.6 The sprintf function

... If copying takes place between objects that overlap, the
behavior is undefined.

It does not say "between /regions/ of objects that overlap". It seems
any overlap is enough to render it undefined.

It seems that the term "object" is not used with great precision here.

What would happen if myvar were defined as
char myvar[2][64] = {"This ..."};
and in the calls to sprintf each use of myvar was cast to char*?
myvar[0] and [1] are objects that do not overlap but both are part of
the object myvar. Is this overlap? Would it be overlap if the
arguments were changed to myvar[0] and myvar[1]?

What about
char *myvar = malloc(128);
strcpy(myvar, "This ...");
There are no objects here so no objects can overlap.

The compiler will probably generate the same code for the three sets
of calls to sprintf. It doesn't seem right (tm) that the same code
generated from essentially identical source statements should be
undefined, questionable, and well defined, respectively.

I will assert that the intent of the word object in this section is
meant to refer to the source and destination strings and therefore
under the conditions I postulated there is no overlap.
These are good points, but I think the wording is clear that the
behaviour is undefined. The intent may not be this wide, but the word
"object" must mean the whole object, surely?

The same wording is used for memcpy, so if it is generally agreed that
memcpy can be used to copy from one place to another non-overlapping
place /within/ a single object, then I agree your solution is OK.

--
Ben.
Jun 27 '08 #40

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2062
by: Uttam | last post by:
Hello, Using ADO I have created a table and have also created fields. To create fields, I have used the following: ..Columns.Append "Field_Name", adWChar, 6 I load records into this created table including into this field.
4
2738
by: mhw | last post by:
I don't found function! Thanks£¡
1
4086
by: Anonieko Ramos | last post by:
> > > How to display multiple spaces in a dropdownlist webform1.aspx <asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>
3
6101
by: Sam | last post by:
I want to divide character into 2 section. Example, 200412 divided into 2004 in A block and 12 in B block. Please advise how to use left(string, length) or right(string, length) for above request. Many thanks in advance.
3
15200
by: NathanC | last post by:
Left('ironman',4) Result - 'iron' Is there anyway to excute this task in VB.NET? Currently, I am determing the value of the 4th character, splitting on that, then grabbing the value of the first part of the split. It works, but is really cumbersome and doesn't account for a string with two consecutive values that are the same, but I might want to include both of them Example: ('neccesarry') Result: 'necce'
2
7242
by: Reny | last post by:
Hi, I came across a doubt on the String.PadLeft Method.The doubt is this -- What's difference it make if the argument to this function carries an integer whose value is less than the length of the string object For example in the sample code below(VB.NET) I could not see any difference
2
1948
by: akoymakoy | last post by:
is there a function to remove leading and trailing spaces on strings? example: word = " THE QUICK BROWN FOX " output: word = "THE QUICK BROWN FOX"
3
4011
by: AWW | last post by:
RichTextBox.Text = string & vbCR works but if I extract a substring with microsoft.visualbasic.left then vbCR stops working. I can do F5 executes with/without the Left and the vbCr does/doesNot work. Comment?
5
3773
by: =?Utf-8?B?Qm9iQWNoZ2lsbA==?= | last post by:
I need a function (or code) that will physically change the words in a text string to make the first word be last, second word next to last, etc. but maintain the same position of the letters in each word. e.g. Before: The dog ran After: ran dog the Is there such a thing?
3
15386
by: Elohim | last post by:
Hi to everybody, I'm a learner of C++. I'll really appreciate if you can help me or teach me something. Thank you in advance. #include<iostream> #include<string> int main() { std::cout << "Introduce your first name:";
0
9528
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10456
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10230
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7548
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6788
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5442
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4118
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.