I'm new at C++ and I'm having problems with saving characters to a string pointer at different locations. Here with this example code, I changed the address of the pointer to point to the 5th location that points to a blank, and I want to be able to save the text "5" there. Can anyone help me?
I changed the address of the pointer to point to the 5th location that points to a blank, and I want to be able to save the text "5" there. Can anyone help me?
The 5th location contains an ending '\0'. If you overwrite that '\0' you're not working with an c-string (zero ended) any more, and you're most likely to run into problems.
- petter
I love deadlines. I like the whooshing sound they make as they pass by - Douglas Adams. Visit me!.
i dont know if it would work but if you replace the \0 with a new string it will add a \0 becuse the new string contains that.
Code:
a = TEXT("1234");
a[5] = TEXT("5"); // or (a + 5)
it wont work. its an array of TCHARS (char's and if unicode an array of unsigned short's)
while TEXT("5") is yet again an array of TCHARS, there is no conversion from an array to an non array i think...
Here is one way to append charaters (or c-strings) to other c-strings.
Code:
// allocate memory for a string (99 charaters + ending zero)
TCHAR* str = new TCHAR[100];
// clear string (set initial character to '\0')
str[0] = _T('\0');
// append data to string
_tcscat(str, _T("some text"));
// print string
_tprintf(_T("%s\n"), str);
// append some more data
_tcscat(str, _T(", some more text"));
// print string
_tprintf(_T("%s\n"), str);
// delete string
delete[] str;
- petter
I love deadlines. I like the whooshing sound they make as they pass by - Douglas Adams. Visit me!.
I'm new at C++ and I'm having problems with saving characters to a string pointer at different locations. Here with this example code, I changed the address of the pointer to point to the 5th location that points to a blank, and I want to be able to save the text "5" there. Can anyone help me?
TCHAR *stringadded = TEXT("1234");
TCHAR *a;
First of all you have to understand the difference between pointer which points to literal string and pointer which points to array of chars.
The fistr case present us with the string which cannot be changed at runtime - in fact such attempt produces access violation exception (at least with VC++7, but unfortunately that dumb VC++6 does not ), since strigng literals are allocated in read-only section.
But the second case gives us exactly what you want:
Code:
#include <windows.h>
int main()
{
TCHAR str[10] = TEXT("1234");
TCHAR *a = str;
a[4] = TEXT('5'); // expand the string
a[5] = TEXT('\0'); // end it with zero
MessageBox(NULL, str, TEXT("Hello2"), MB_OKCANCEL);
return 0;
}
Here we have an array initialized with the string - initialization makes the exact string copy at new location, and that new string can be expanded within array.
Last edited by Igor Vartanov; January 2nd, 2006 at 03:01 PM.
Bookmarks