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 12469
pete <pf*****@mindsp ring.comwrites:
nospam wrote:
>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";
/* BEGIN new.c */
#include <stdio.h>
int main(void)
{
char myvar[128] = "This is a string";
sprintf(myvar, "%20s", "This is a string");
puts(myvar);
return 0;
}
/* END new.c */
And what if the declaration is changed to:
char myvar[128] = "This is a string too";
? The requirement is to insert 4 spaces, not to deal just with that
one particular string. If it were, the sprintf call could be changed
to:
strcpy(myvar, " This is a string");
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
On 10 Jun, 02:48, nospam <n...@spam.comw rote:
On Mon, 09 Jun 2008 23:28:17 +0000, Jens Thoms Toerring wrote:
nospam <n...@spam.comw rote:
If I have a string say:
myvar[128] = "This is a string";
I guess that's supposed to be
char 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";
sprint() doesn't convert strings, it prints into a string.
It looks as if you would like to use sprintf() with 'myvar'
as both the source and the destination and that's not pos-
sible. The C standard says about this specifically:
* If copying takes place between objects that overlap,
* the behavior is undefined.
which exactly addresses this situation. So there's no way
you can do this reliably with sprintf().
I guess in the end you want to do something more complicated
but for what you describe you want to do a simple
memmove( myvar + 4, myvar, strlen( myvar ) + 1 );
memset( myvar, ' ', 4 );
will do. Note the use of memmove() instead of memcpy() which
is required since source and destination overlap.
* * * * * * * * * * * * * * Regards, Jens
I need to use sprintf, similar to the legacy code I'm working with.
Something like this:
strncpy(fname,t mp+21,9); fname[9] = '\0';
strncpy(mname,t mp+31,1); mname[1] = '\0';
sprintf(tmp,"%4 s%-20s%-20s%-32s%-4s",
* * * * * * " ",fname,mname,l name," ");- Hide quoted text -
why do you need to use sprintf()?
(several other people have asked you this but you didn't reply)
--
Nick Keighley
"rio" <a@b.cha scritto nel messaggio
news:48******** *************** @reader2.news.t in.it...
>
"nospam" <no@spam.comh a scritto nel messaggio
news:co******** *************** *******@comcast .com...
>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!
it not use sprint not tested
/* return the string if ok
0 if error
using like:
char *pc;
char *s="This is a string"
if((pc=the4spac es(s))==0) Error();
use(pc);
....
free(pc);
*/
char* the4spaces(char * s)
{char *p1, *p2, p;
unsigned c, sz;
/*************** *****/
if(s==0) return 0;
if( (int) (sz=strlen(s)) < 0) return 0;
p=p2=malloc(sz+ 8);
if(p2==0) return 0;
p1=s;
while( *p1 && (*p1==' '||*p1=='\t')) ++p1;
*p2++=' '; *p2++=' '; *p2++=' '; *p2++=' ';
while(*p2++=*p1 ++);
return p;
}
the CBFalconer way
/*
sz is the space memory size
not tested
*/
unsigned the4spaces(char * s, unsigned sz)
{char *p1, *p2;
unsigned c;
/*************** *****/
if(s==0) return 1; /* nothing error */
if((int)sz<=4) return 2; /* error */
c=strlen(s);
if(c<0 || c+4>=sz) return 3;
p1=s+c+4; p2=s+c;
while(p2>=s) {*p1=*p2; --p1; --p2;}
s[0]=' '; s[1]=' '; s[2]=' '; s[3]=' ';
return 0; /* ok */
}
/*
one better version?
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);
----------
*/
unsigned the4spaces(char ** d, unsigned sz, char* s)
{char *p1, *p2, p;
unsigned c, sz, r;
/*************** *****/
if(s==0) goto l0;
if( (int) (c=strlen(s)) < 0)
goto l0;
r=sz;
if(c+4+1<sz)
{if( p=realloc(*d, c+8)==0)
{l0:;
free(*d); *d=0; return 0;
}
r=c+8;
}
p1=s; p2=p; *d=p;
while( *p1 && (*p1==' '||*p1=='\t')) ++p1;
*p2++=' '; *p2++=' '; *p2++=' '; *p2++=' ';
while(*p2++=*p1 ++);
return r;
}
"rio" <a@b.cha scritto nel messaggio news:484e3100$0 $18150/*
one better version?
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);
----------
*/
unsigned the4spaces(char ** d, unsigned sz, char* s)
{char *p1, *p2, p;
unsigned c, sz, r;
/*************** *****/
if(s==0) goto l0;
if( (int) (c=strlen(s)) < 0)
goto l0;
r=sz;
p=*d;
if(c+4+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; *d=p;
^^^^^^^not
p1=s; p2=p;
while( *p1 && (*p1==' '||*p1=='\t')) ++p1;
*p2++=' '; *p2++=' '; *p2++=' '; *p2++=' ';
while(*p2++=*p1 ++);
return r;
}
nospam <no@spam.comwro te:
On Mon, 09 Jun 2008 23:28:17 +0000, Jens Thoms Toerring wrote:
nospam <no@spam.comwro te:
If I have a string say:
myvar[128] = "This is a string";
I guess that's supposed to be
char 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";
I need to use sprintf, similar to the legacy code I'm working with.
Something like this:
strncpy(fname,t mp+21,9); fname[9] = '\0';
strncpy(mname,t mp+31,1); mname[1] = '\0';
sprintf(tmp,"%4 s%-20s%-20s%-32s%-4s",
" ",fname,mname,l name," ");
This one is fine since before your print into tmp you
obviously copy the bits from tmp you still need to some
other place. And then you write something completely
new into tmp, using what you had copied to a safe place.
So if you would have a second array to store what myvar
holds, then of course you can print into myvar afterwards
with sprintf() like in
char myvar[ 128 ] = "This is a string";
char buf[ 124 ];
strncpy( buf, myvar, 123 );
buf[ 123 ] = '\0';
sprintf( myvar, " %s", buf );
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
On 10 Jun 2008 at 0:04, CBFalconer wrote:
if (amount) {
pi = strchr(s, '\0');
if ((p1 s) && amount) {
Got to love this. A condition as redundant as it is ugly.
Richard Heathfield <rj*@see.sig.in validwrites:
Ben Bacarisse said:
>Richard<rg**** @gmail.comwrite s:
>>Ben Bacarisse <be********@bsb .me.ukwrites:
<snip>
>>>void sstretch(char *s, size_t amount) { memmove(s + amount, s, strlen(s) + 1); memset(s, ' ', amount); }
I would also point out to the beginner, and "Chuck", to read the man pages and to see why memmove is better than memcpy in this and other situations.
That is an odd way of putting it. memmove is *essential* in this situation.
Um, no, it isn't. You /can/ bully the bytes around by hand if you prefer
(but if you do so, you need to push them *just so*, or they'll turn on
you). If you just meant that memcpy is a non-starter here, then of course
I agree.
What do you think, seriously? Did you think I had forgotten, for a
moment, that one could just move the data about "by hand"? Were you
worried that people new to C would take that remark and think that
there was absolutely only one function that can be used here[1]? It was
in a direct reply to "memmove is better than memcpy".
Does every statement have to true when clipped out of context? If I
had instead used your phrase "memcpy is a non-starter here" would you
have come back with "Um, no. You /can/ use an auxiliary array."?
[1] OK, so you can tell I am little annoyed by this level of nit-
picking so here is a related story to lighten the tone: When I was
about six and I heard a pipe band was playing "Scotland the Brave".
It seemed they always played that, so I asked my father if this is the
only tune the bagpipes can play. He replied, voice no doubt dripping
with sarcasm, "Yes, it's a musical instrument that can only play one
tune". The sarcasm went right over my six year old head and I for
years, whenever I head the pipes I used to think "that must be another
part of Scotland the Brave I don't know". Logic forced me to assume
it was the longest tune ever written.
So, yes, beginners can be thrown by authoritative statements taken out
of context, but I dispute that that was a real and present danger in
this case.
--
Ben.
"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?
--
Ben.
Ben Bacarisse said:
Richard Heathfield <rj*@see.sig.in validwrites:
>Ben Bacarisse said:
<snip>
>>> That is an odd way of putting it. memmove is *essential* in this situation.
Um, no, it isn't. You /can/ bully the bytes around by hand if you prefer (but if you do so, you need to push them *just so*, or they'll turn on you). If you just meant that memcpy is a non-starter here, then of course I agree.
What do you think, seriously?
That your (previous) reply was composed and posted swiftly.
Did you think I had forgotten, for a
moment, that one could just move the data about "by hand"?
No.
Were you
worried that people new to C would take that remark and think that
there was absolutely only one function that can be used here[1]?
Yes.
It was in a direct reply to "memmove is better than memcpy".
Yes, I know, but it was also rather poorly worded.
Does every statement have to true when clipped out of context?
I left the context in place, but I still think that "essential" is a
sufficiently forceful word that there was a risk of its overwhelming that
context, which is why I replied as I did.
If I
had instead used your phrase "memcpy is a non-starter here" would you
have come back with "Um, no. You /can/ use an auxiliary array."?
I don't think so, no - memcpy /is/ a non-starter because you have to do the
byte shuffle - into temp, then back into the original array - and whilst
that's doable, it's a bit lame.
[1] OK, so you can tell I am little annoyed by this level of nit-
picking
You might want to pick up a slightly thicker skin from Tesco or Sears or
wherever. I've been nitpicked a lot worse than that, and lived to tell the
tale. :-)
so here is a related story to lighten the tone: When I was
about six and I heard a pipe band was playing "Scotland the Brave".
It seemed they always played that, so I asked my father if this is the
only tune the bagpipes can play. He replied, voice no doubt dripping
with sarcasm, "Yes, it's a musical instrument that can only play one
tune". The sarcasm went right over my six year old head
Parents really can be [********] sometimes, can't they?
<snip>
So, yes, beginners can be thrown by authoritative statements taken out
of context, but I dispute that that was a real and present danger in
this case.
I think you'd have been right to dispute it, say, ten years ago, or maybe
even five.
--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
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:
void sstretch(char *s, size_t amount) { memmove(s + amount, s, strlen(s) + 1); memset(s, ' ', amount); }
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.
Incidentally, a speed comparison would be interesting. I don't
think your version allows for amount == 0
I disagree, but if you think there is a problem, please quote C&V --
it seem fine by my reading. While we are being incidental, your code
does not check for amount < 0 but I decided that was not a bug but an
undocumented contract with the caller.
and for an empty original
string.
How ironic. You code breaks in that case. What problem do you see in
my version? As I say, it seems fine by my reading of the standard but
I am open to wiser interpretations .
I would have to check the specs for memove and memset with
care.
That would seem to be a staring point, not something to leave until
after you've suggested someone else is wrong.
--
Ben. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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.
|
by: mhw |
last post by:
I don't found function!
Thanks£¡
|
by: Anonieko Ramos |
last post by:
>
>
>
How to display multiple spaces in a dropdownlist
webform1.aspx
<asp:DropDownList id="DropDownList1"
runat="server"></asp:DropDownList>
|
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.
|
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'
| |
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
|
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"
|
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?
|
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?
|
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:";
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
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,...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |