Thread: Converting wstring bytes to string...

  1. #1
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204

    Thumbs up Converting wstring bytes to string...

    I'm trying to get the bytes from a std::wstring and put them into a std::string. Unfortunately, I'm somewhat lacking when it comes to c-style string. I've made this code (and it works), but is there an easier (and more efficient) way?

    Code:
    std::string WideStringToStringStrict( const std::wstring& Text )
    {
    	unsigned int Size = Text.size() * sizeof( wchar_t );
    	char* ctemp = new char[Size];
    	memcpy( ctemp, Text.c_str(), Size );
    	std::string String;
    	for ( unsigned int i = 0; i < Size; ++i )
    		String += ctemp[i];
    	delete[] ctemp;
    	return String;
    };
    Thanks.

  2. #2
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    What is this?
    Do you really want to copy byte-by-byte wstring to string?
    Or convert each of the wstring's element to its string's element equivalent (so the size of the string will be X times less)?

    For the first one I see no point.

    And you don't need any buffer for this (your code leaks memory in case the += operator throws an exception).

    Code:
    std::string wtoa(const std::wstring& wide)
    {
        std::string str;
        for(std::wstring::const_iterator it = wide.begin();
            it != wide.end();
            ++it)
        {
            str.push_back(static_cast<char>(*it));
        }
        return str;
    }
    Haven't tested it, but something like this.
    Last edited by kmdv; 10-16-2010 at 04:42 PM.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I couldn't resist
    My version:
    Code:
    std::string wtoa(const std::wstring& wide)
    {
        std::string out;
        std::transform(wide.begin(), wide.end(), std::back_inserter(out),
            [](wchar_t ch) -> char { return static_cast<char>(ch); });
        return out;
    }
    Of course, not tested.
    By yours truly.
    Last edited by Elysia; 10-16-2010 at 06:09 PM. Reason: Bug fix
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204
    @kmdv: I specifically need the extra byte from the wchar_t.

    @Elysia: Jesus of Nazareth, my brain overheats just trying to understand that std::transform function. Pity it won't compile.

    I get the feeling that this isn't an easy (or common) task. I guess I'll have to stick with mine or try to fix it up later.

    Thanks for the help.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It compiles fine. Just a small typo there: whar_t should of course be wchar_t.
    Also make sure to include necessary headers:

    #include <string>
    #include <iterator>
    #include <algorithm>

    The function isn't all that complicated either. All it does is take an input range (first two parameters), an output iterator, and a function to perform the "transformation".
    Then all it does is for each it in [begin, end), *out = transform(*it).

    Also, in case you need the extra byte, then this should suffice:
    Code:
    std::string wtoa(const std::wstring& wide)
    {
        std::string out;
        std::copy(wide.begin(), wide.end(), std::back_inserter(out));
        return out;
    }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Registered User
    Join Date
    Dec 2008
    Location
    Black River
    Posts
    128
    Code:
    std::string wtoa (const std::wstring& wstr)
    {
       return (std::string(wstr.begin(), wstr.end()));
    }
    Much better, imo.

    But, all in all, I'd seriously question the idea of converting from wchar_t into char without considering encodings or even the case of a wchar_t greater than CHAR_MAX.
    Last edited by Ronix; 10-16-2010 at 06:57 PM.
    Stick close to your desks and never program a thing,
    And you all may sit in the standards commitee!

  7. #7
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by Elysia View Post
    I couldn't resist
    My version:
    Code:
    std::string wtoa(const std::wstring& wide)
    {
        std::string out;
        std::transform(wide.begin(), wide.end(), std::back_inserter(out),
            [](wchar_t ch) -> char { return static_cast<char>(ch); });
        return out;
    }
    Of course, not tested.
    By yours truly.
    What the holy hell is that?? It looks more like Groovy code than C++. Is it some kind of C++0x syntax?
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by cpjust
    What the holy hell is that?? It looks more like Groovy code than C++. Is it some kind of C++0x syntax?
    Lambda function syntax from the next version of C++. Considering that Ronix's suggestion should be one of the first things that come to mind, I suspect Elysia was just looking for an excuse to demonstrate the use of a lambda function
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Why is lambda so fugly in this language? Couldn't they use lambda or something?

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Ronix View Post
    Code:
    std::string wtoa (const std::wstring& wstr)
    {
       return (std::string(wstr.begin(), wstr.end()));
    }
    Much better, imo.

    But, all in all, I'd seriously question the idea of converting from wchar_t into char without considering encodings or even the case of a wchar_t greater than CHAR_MAX.
    Ahhh, that's even better. Damn, I didn't think of that.

    Quote Originally Posted by laserlight View Post
    Lambda function syntax from the next version of C++. Considering that Ronix's suggestion should be one of the first things that come to mind, I suspect Elysia was just looking for an excuse to demonstrate the use of a lambda function
    Actually, I thought I'd use std::transform for this purpose instead of writing long unnecessary code that does the same thing. Why not use the standard library when you can?
    But std::transform requires a function to do the conversion, or transformation, so I stuck in a lambda to do the work.

    Quote Originally Posted by whiteflags View Post
    Why is lambda so fugly in this language? Couldn't they use lambda or something?
    Dunno. They don't look so ugly to me.
    The reason they didn't use lambda is probably to avoid introducing a new keyword.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM