Friday, May 6, 2011

Need help appending one wchar_t to another! C++

I have tried wcscat() but i get a runtime access violation.

wchar_t* a = L"aaa";
wchar_t* b = L"bbb";
wchar_t* c;
c = wcscat(a, b);

Can somebody tell me what is wrong here? Or another way to solve my problem? Thanks

From stackoverflow
  • Use c++'s built in wstring:

    #include <string>
    using std::wstring;
    
    int main()
    {
        wstring a = L"aaa";
        wstring b = L"bbb";
        wstring c = a + b;
    }
    

    wcscat is for c-style strings, not c++ style strings. The c way to do this is

    wchar_t* a = L"aaa";
    wchar_t* b = L"bbb";
    wchar_t c[7];
    wcscpy(c, a);
    wcscat(c, b);
    

    EDIT: Wow, now that I edited it, it makes it look like I copied one of the answers below.

    Greg Hewgill : It must have been the correct solution then! :)
  • The wcscat function appends the second argument onto the string buffer in the first argument. It looks as though this might be your first experience using strings in C. You could make your example work by doing the following:

    wchar_t* a = L"aaa";
    wchar_t* b = L"bbb";
    wchar_t c[7];
    wcscpy(c, a);
    wcscat(c, b);
    

    When using C string manipulation functions, you must ensure that you allocate enough buffer space for the string operation begin performed (the C runtime won't do it for you). In this case, it means the c buffer must contain enough space to hold the result string. I have precalculated that the result is 6 characters long plus the trailing null, which means I need to allocate 7 characters.

  • wcscat doesn't create a new string - it simply appends b to a. So, if you want to make sure you don't cause a runtime access violation, you need to make sure there's space for b at the end of a. In the case above:

    wchar_t a[7] = L"aaa";
    wchar_t b[]  = L"bbb";
    wchar_t* c;
    c = wcscat(a, b);
    

    You can still get a return value from the function, but it will simply return a.

  • Why not use std::wstring? Here's a great answer explaining it.

    Here is your code with wstring:

    #include <string>
    
    int main(void)
    {
        std::wstring a(L"aaa");
        std::wstring b(L"bbb");
    
        std::wstring c = a + b;
    
        return 0;
    }
    

    To answer your actual question though, you are using wcscat incorrectly. Try like this:

    #include <string>
    
    int main(void)
    {
        // constant wchar_t
        const wchar_t *a = L"aaa";
        const wchar_t  *b = L"bbb";
    
        // buffer for concatenation, could change to a call to new
        wchar_t c[50] = {0};
    
        // add a to c, then b to c (ending up with a + b)
        wcscat(c, a);
        wcscat(c, b);
    
        // would free memory here if you used new
        return 0;
    }
    

0 comments:

Post a Comment