How can I make a string a certain length by filling the remaining spaces with a certain character? For example, if I wanted each string to have 7 characters, "hello" becomes "__hello", "123" becomes "____123", etc.
Printable View
How can I make a string a certain length by filling the remaining spaces with a certain character? For example, if I wanted each string to have 7 characters, "hello" becomes "__hello", "123" becomes "____123", etc.
PHP Code:#include <iostream>
using namespace std;
int main()
{
char a[6]="hello";
char b[8];
char* m=b+sizeof(b)-sizeof(a);
for (char* i=b;i<m;*i++='_');
for (char* j=a;i<b+sizeof(b);*i++=*j++);
cout << b << endl;
return 0;
}
The reason I was asking is because I an trying to write a program that converts text to binary and if i get "101010" i need to add the other zero's on. I am generating the string i want to add to in a loop, so is it possible to do it that way?
Yes but this also puts it in another light, you can do it more efficiently with some bitshifts and bitwise and's
This is from memory - we have a bunch of these - lpad, rpad,
zf (zero-fill), etc.
PHP Code:#include <string.h>
void zf(char *t, int i);
void lpad(char *t, int i, char *padchar));
/* lpad - add spaces on left side of char */
/* standard ansi c */
/* you can modify this to pad with any char */
void lpad(char *t, int i, char *padchar) {
char tmp[8192];
int j;
if (strlen(t) > i || strlen(t) == i) return;
while (strlen(t) < i){
strcpy(tmp,padchar);
strcat(tmp,t);
strcpy(t,tmp);
}
}
void zf(char *t, int i){
lpad(t,i);
}
:eek:Quote:
Originally posted by jim mcnamara
PHP Code:char tmp[8192];
Some code sends down special strings that are kinda long.
We have to make sure it always works.
I know that allocating a lot of memory is supposed to be harder on the OS, but in Windows, any memory allocation request up to 8192 bytes uses the same amount of os overhead, because of the way P1 space has the memory masthead list.
It's a complete waste of memory for what Wynd wants. It isn't for us.
Did you write those?
Unfortunately.
We have a big lib of functions for strings, barcodes and so on.
They have to conform to some wierd criteria, like running on several platforms, and supporting some bizrre recordtypes, hence the ansi c compliance.
you could use fill().
Code:#include <iostream.h>
int main()
{
using namespace std;
cout.width(10);
cout.fill('*');
cout<<"Hi";
return 0;
}
Thanks, that function works :)