Adding characters to the front of strings

Hi

Within my program, I need a string array to be 8 characters in length. The string, when input, is not necessarily 8 characters, and therefore i need to add '0' to the front of the string to increase its length to 8, and move the existing content up so that it is on the end of the string.

For example, if an input was 111, it is necessary that I manipulate the string to 00000111.

The method must be dynamic, to deal with inputs larger and smaller than 3.
I am new to C++, so thanks in advance.
if you are using string it's very easy:

1
2
3
4
5
string example = "111";
while(example.length() < 8)
{
  example = "0" + example;
}
Are you using std::string or char arrays?
char arrays
This should work:
1
2
3
4
5
char arr[8] = "111"; // C string you want to modify
int len = 8-strlen(arr); // get the missing part size
memmove(arr+len,arr,strlen(arr)); // move the string characters to the end
for ( int i = 0; i < len; i++ ) // fill the beginning characters with '0'
    arr[i] = '0';

http://www.cplusplus.com/reference/clibrary/cstring/memmove/
Problem solved, thanks.
Topic archived. No new replies allowed.