Re: std::string
От: korzhik Россия  
Дата: 25.10.05 07:23
Оценка: 3 (1)
Здравствуйте, Аноним, Вы писали:

А>подскажите пожалуйста, как преобразовать std::string в std::wstring и обратно, желательно средствами stl или boost (без прямого вызова MultiByteToWideChar)?

посмотри этот файлик, правда я не тестировал...
// boost/string_conversion.hpp
// <!!-----------------------------------------------------------------------> 
// <!! Copyright © 2001 Dietmar Kuehl, All Rights Reserved                   > 
// <!!                                                                       > 
// <!! Permission to use, copy, modify, distribute and sell this             > 
// <!! software for any purpose is hereby granted without fee, provided      > 
// <!! that the above copyright notice appears in all copies and that        > 
// <!! both that copyright notice and this permission notice appear in       > 
// <!! supporting documentation. Dietmar Kuehl makes no representations about> 
// <!! the suitability of this software for any purpose. It is provided      > 
// <!! "as is" without express or implied warranty.                          > 
// <!!---------------------------------------------------------------------- > 
// Author: Dietmar Kuehl (dietmar_kuehl@yahoo.com) 
// Revised by Jan Langer (jan@langernetz.de)
// --------------------------------------------------------------------------- 

#ifndef BOOST_STRING_CONVERSION_HPP
#define BOOST_STRING_CONVERSION_HPP

#include "boost/config.hpp"

// --------------------------------------------------------
// if no locale is available 
// provide a simple implementation

#ifndef BOOST_NO_STD_LOCALE
#include <locale>
using std::locale;
using std::use_facet;
using std::ctype;
#else
namespace
{
  struct locale {};

  template <class T> T use_facet(locale const&) 
  { 
    return T(); 
  }
  
  template <class CharT> 
  struct ctype 
  {
    char narrow(CharT c, char) const 
    { 
      return char (c); 
    }
    CharT widen (char c) const 
    { 
      return CharT (c); 
    }
  };
}
#endif
            
#include <string>

namespace boost
{
    namespace detail
    {
      // --------------------------------------------------
      // char conversion by means of ctype's widen and narrow
      // uses widen if cFrom=char 
      // uses narrow if cTo=char
      // returns just the argument in all other cases
      // --------------------------------------------------
      
      // general case
      template <class cTo, class cFrom>
      struct char_conversion
      {
        static cTo
        convert (cFrom c, locale const & = locale ())
    {
      return c;
    }
      };
      
      // conversion from cFrom to char with narrow
      template <class cFrom>
      struct char_conversion <char, cFrom>
      {
        static char
        convert (cFrom c, locale const &loc = locale ())
    {
          ctype <cFrom> const &ct = use_facet <ctype <cFrom> > (loc);
          return ct.narrow (c, '.');
        }
      };

      // conversion from char to cTo with widen
      template <class cTo>
      struct char_conversion <cTo, char>
      {
        static cTo
        convert (char c, locale const &loc = locale ())
    {
          ctype <cTo> const &ct = use_facet <ctype <cTo> > (loc);
          return ct.widen (c);
        }
      };

      // conversion from char to char
      // general case be fit, but is less specialized than the other 
      // specializations
      template <>
      struct char_conversion <char, char>
      {
        static char
        convert (char c, locale const & = locale ())
    {
      return c;
    }
      };

      // --------------------------------------------------
      // string conversion with the help of char_conversion
      // just returns if cTo=cFrom
      // --------------------------------------------------
      
      // general case
      template <class cTo, class cFrom>
      struct string_conversion
      {
        static std::basic_string <cTo> 
        convert (std::basic_string <cFrom> const &s, 
             locale const &loc = locale ())
        {
          std::basic_string <cTo> rc (s.size (), cTo ());
          for (typename std::basic_string <cFrom>::size_type i = 0; i < s.size (); ++i)
          {
            rc [i] = char_conversion <cTo, cFrom>::convert (s [i], loc);
          }
          return rc;
        }
      };

      // if cTo==cFrom
      template <class cTo>
      struct string_conversion <cTo, cTo>
      {
        static std::basic_string <cTo> 
        convert (std::basic_string <cTo> const &s, 
             locale const & = locale ())
        {
      return s;
        }
      };
    
    } // namespace detail

    // ----------------------------------------------------
    // string_cast

    template <class cTo, class cFrom>
    std::basic_string <cTo> string_cast (
               std::basic_string <cFrom> const &str, 
               locale const &loc = locale ())
    {
      return detail::string_conversion <cTo, cFrom>::convert(str, loc);
    }
    template <class cTo, class cFrom>
    std::basic_string <cTo> string_cast (
               cFrom const *s,
           locale const &loc = locale ())
    {
      return string_cast <cTo, cFrom> (s, loc);
    }

    // ----------------------------------------------------
    // char_cast
    
    template <class cTo, class cFrom>
    cTo char_cast(cFrom c, locale const& loc = locale ())
    {
      return detail::char_conversion <cTo, cFrom>::convert (c, loc);
    }

    // ----------------------------------------------------

} // namespace boost

#endif // BOOST_STRING_CONVERSION_HPP
Re[3]: std::string
От: korzhik Россия  
Дата: 12.11.05 17:39
Оценка: 2 (1)
Здравствуйте, MuTPu4, Вы писали:

MTP>Собственно, возник вопрос каков статус этого файлика и где он был взят. Я так понимаю из CVS/Sandbox CVS или еще откуда-то?


Отсюда http://groups.yahoo.com/group/boost/files/
Зарегистрироваться надо только.
Re[3]: std::string
От: GregZ СССР  
Дата: 25.10.05 06:46
Оценка: 1 (1)
Здравствуйте, Аноним, Вы писали:

А>не правильно написал:

А>int a=5;
А>std::string s="test";
А>std::string d;
А>d=s+a;

А>для std::string оператор + int тоже не определен?

А>а как еще можно преобразовать, кроме itoa?

можно пользоваться строковыми потоками


int a=5;
std::string s="test";

std::stringstream ss;
ss << s << a;
std::string d = ss.str();
std::string
От: Аноним  
Дата: 25.10.05 06:01
Оценка:
подскажите пожалуйста, как преобразовать std::string в std::wstring и обратно, желательно средствами stl или boost (без прямого вызова MultiByteToWideChar)?

и еще, как std::string (std::wstring) присвоить int?
( строка типа
int a=5;
std::string s="test"+a;
дает ошибку
)
Re: std::string
От: ilsd  
Дата: 25.10.05 06:31
Оценка:
Здравствуйте, Аноним, Вы писали:

А>подскажите пожалуйста, как преобразовать std::string в std::wstring и обратно, желательно средствами stl или boost (без прямого вызова MultiByteToWideChar)?


А>и еще, как std::string (std::wstring) присвоить int?

А>( строка типа
А>int a=5;
А>std::string s="test"+a;
А>дает ошибку
А>)

По второй части:
char* + int -- оператор "+" не определен.
нужно преобразовать int к строке, а уже потом прибавлять.
Причем не к char* опять же, а к string.

best...
Re[2]: std::string
От: Аноним  
Дата: 25.10.05 06:41
Оценка:
Здравствуйте, ilsd, Вы писали:

I>По второй части:

I>char* + int -- оператор "+" не определен.
I>нужно преобразовать int к строке, а уже потом прибавлять.
I>Причем не к char* опять же, а к string.

I>best...


не правильно написал:
int a=5;
std::string s="test";
std::string d;
d=s+a;

для std::string оператор + int тоже не определен?
а как еще можно преобразовать, кроме itoa?
Re: std::string
От: remark Россия http://www.1024cores.net/
Дата: 25.10.05 07:14
Оценка:
Здравствуйте, Аноним, Вы писали:

А>подскажите пожалуйста, как преобразовать std::string в std::wstring и обратно, желательно средствами stl или boost (без прямого вызова MultiByteToWideChar)?


mbcstowcs()
wcstombcs()

локаль устанавливать с помощью setlocale()

правда в msvc они рано или поздно всё равно вызывают MultiByteToWideChar()


1024cores &mdash; all about multithreading, multicore, concurrency, parallelism, lock-free algorithms
Re: std::string
От: Аноним  
Дата: 25.10.05 08:07
Оценка:
Спасибо за помощь!
использование mbstowcs/wcstombs/setlocale будет работать под другой платформай, отличной от ms windows?
Re[2]: std::string
От: remark Россия http://www.1024cores.net/
Дата: 25.10.05 08:17
Оценка:
Здравствуйте, Аноним, Вы писали:

А>Спасибо за помощь!

А>использование mbstowcs/wcstombs/setlocale будет работать под другой платформай, отличной от ms windows?

В стандарте, в разделе standart functions эти функции есть


1024cores &mdash; all about multithreading, multicore, concurrency, parallelism, lock-free algorithms
Re[2]: std::string
От: maggres Россия  
Дата: 25.10.05 08:38
Оценка:
Здравствуйте, Аноним, Вы писали:

А>Спасибо за помощь!

А>использование mbstowcs/wcstombs/setlocale будет работать под другой платформай, отличной от ms windows?

Да, вполне успешно работает под Linux
Re: std::string
От: Июнь  
Дата: 25.10.05 09:01
Оценка:
Здравствуйте, <Аноним>, Вы писали:

А>подскажите пожалуйста, как преобразовать std::string в std::wstring и обратно, желательно средствами stl или boost (без прямого вызова MultiByteToWideChar)?


Посмотри Re: конвертация std::string в std::wstring
Автор: _AK_
Дата: 09.07.04
Re: std::string
От: Jax Россия  
Дата: 25.10.05 09:14
Оценка:
Здравствуйте, Аноним, Вы писали:

А>подскажите пожалуйста, как преобразовать std::string в std::wstring и обратно, желательно средствами stl или boost (без прямого вызова MultiByteToWideChar)?


// ctype_widen.cpp
// compile with: /EHsc
#include <locale>
#include <iostream>
using namespace std;

int main( )   
{
   locale loc1 ( "English" );
   char *str1 = "Hello everyone!";
   wchar_t str2 [16];
   bool result1 = use_facet<ctype<wchar_t> > ( loc1 ).widen
      ( str1, str1 + strlen(str1), &str2[0] );
   str2[strlen(str1)] = '\0';
   cout << str1 << endl;
   wcout << &str2[0] << endl;

   ctype<wchar_t>::char_type charT; // how to use this as a return?
   charT = use_facet<ctype<char> > ( loc1 ).widen( 'a' );

   //cout << charT << endl;
}


Взято:
(ctype::widen)
ms-help://MS.VSCC.2003/MS.MSDNQTR.2005APR.1033/vcstdlib/html/vclrf_locale_Ctypewiden.htm
Re[3]: std::string
От: MShura  
Дата: 10.11.05 19:10
Оценка:
А>>использование mbstowcs/wcstombs/setlocale будет работать под другой платформай, отличной от ms windows?

M>Да, вполне успешно работает под Linux


Только надо помнить, что под Linux размер wchar_t равен 4 байта.
Если задать компилятору -fshort-wchar, wchar-t станет 2 байта, но естественно конвертация строк типа L"Hello" станет работать неправильно.
Re[2]: std::string
От: MuTPu4  
Дата: 12.11.05 15:21
Оценка:
Здравствуйте, korzhik, Вы писали:

K>посмотри этот файлик, правда я не тестировал...

K>...

После исправления опечатки:
return detail::string_conversion <cTo, cFrom>::convert (s, loc);

вместо
return string_cast <cTo, cFrom> (s, loc);

стал использовать у себя и пока доволен, спасибо

Собственно, возник вопрос каков статус этого файлика и где он был взят. Я так понимаю из CVS/Sandbox CVS или еще откуда-то?
... << RSDN@Home 1.1.4 stable SR1 rev. 568>>
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.