С Новым годом! Форум программистов, компьютерный форум, киберфорум
Boost C++
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.63/8: Рейтинг темы: голосов - 8, средняя оценка - 4.63
 Аватар для artem78
6 / 8 / 2
Регистрация: 20.12.2012
Сообщений: 729

Ошибка преобразования wsmatch в CString

09.06.2013, 00:20. Показов 1635. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
С использованием библиотеки boost написал функцию получения имени хоста по урл.
Компилируется нормально, но при выполнении на return-е всплывает вот это:
Code
1
2
3
4
5
6
7
 Debug Assertion Failed!
 
 Program: ...ы\Visual Studio 2010\Projects\HTTPClient\Debug\HTTPClient.exe
 File: c:\program files\microsoft visual studio 10.0\vc\include\xstring
 Line: 249
 
 Expression: string iterators incompatible
Код функции getHostName:
C++
1
2
3
4
5
6
7
8
9
10
CString CHTTPClientDlg::getHostName(CString url) {
    using namespace boost;
 
    wregex re(L"^(?:http:\/\/)?([^\/]*)");
    wsmatch host;
 
    regex_search((std::wstring) (url.GetString()), host, re);
 
    return CString((std::wstring(host[1])).c_str());
}
Объясните, что значит эта ошибка и как это исправить?
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
09.06.2013, 00:20
Ответы с готовыми решениями:

CString::Format() и преобразование double в CString
Вот фрагмент программы: void CMy6_1Dlg::OnRadio3() { CString s; int i=m_list1.GetCount(); int a; int k=0; float...

Ошибка. Невозможно преобразовать CString в float
Здравствуйте! Программа заключается в следующем - пользователь добавляет в EditControl данные, нажимает на ОК, и эти данные попадают в...

Ошибка при преобразовании CString в CTime
Пытаюсь конвертировать строку даты в тип даты, ошибка выходит при исполнения кода CString str="26/06/2014"; CTime dt; ...

4
Ушел с форума
Эксперт С++
 Аватар для Убежденный
16481 / 7444 / 1187
Регистрация: 02.05.2013
Сообщений: 11,616
Записей в блоге: 1
09.06.2013, 12:05
Приведения типов в стиле С - зло !
Они "насильно" приводят один тип к другому, даже там, где это лишено смысла
или вообще ошибочно, причем все это происходит без предупреждений компилятора.

Попробуйте переписать данный код, не используя приведения типов.
И увидите, где ошибки.
0
 Аватар для artem78
6 / 8 / 2
Регистрация: 20.12.2012
Сообщений: 729
09.06.2013, 13:39  [ТС]
Переписал:
C++
1
2
3
4
5
6
7
8
9
10
CString CHTTPClientDlg::getHostName(CString url) {
    using namespace boost;
 
    wregex re(L"^(?:http:\/\/)?([^\/]*)");
    wsmatch host;
 
    regex_search(url, host, re);
 
    return host[1];
}
Если так, тогда вообще ничего не понятно:
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
          c:\program files\microsoft visual studio 10.0\vc\include\string.h(105) : see declaration of 'strcpy'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(125): warning C4129: '/' : unrecognized character escape sequence
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(125): warning C4129: '/' : unrecognized character escape sequence
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(125): warning C4129: '/' : unrecognized character escape sequence
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(128): error C2784: 'bool boost::regex_search(const std::basic_string<charT,ST,SA> &,const boost::basic_regex<charT,traits> &,boost::regex_constants::match_flag_type)' : could not deduce template argument for 'const std::basic_string<charT,ST,SA> &' from 'CString'
          c:\boost_1_50\boost\regex\v4\regex_search.hpp(159) : see declaration of 'boost::regex_search'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(128): error C2784: 'bool boost::regex_search(const std::basic_string<charT,ST,SA> &,const boost::basic_regex<charT,traits> &,boost::regex_constants::match_flag_type)' : could not deduce template argument for 'const std::basic_string<charT,ST,SA> &' from 'CString'
          c:\boost_1_50\boost\regex\v4\regex_search.hpp(159) : see declaration of 'boost::regex_search'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(128): error C2784: 'bool boost::regex_search(const charT *,const boost::basic_regex<charT,traits> &,boost::regex_constants::match_flag_type)' : could not deduce template argument for 'const charT *' from 'CString'
          c:\boost_1_50\boost\regex\v4\regex_search.hpp(151) : see declaration of 'boost::regex_search'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(128): error C2782: 'bool boost::regex_search(BidiIterator,BidiIterator,const boost::basic_regex<charT,traits> &,boost::regex_constants::match_flag_type)' : template parameter 'BidiIterator' is ambiguous
          c:\boost_1_50\boost\regex\v4\regex_search.hpp(135) : see declaration of 'boost::regex_search'
          could be 'boost::wsmatch'
          or       'CString'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(128): error C2784: 'bool boost::regex_search(const std::basic_string<charT,ST,SA> &,boost::match_results<std::basic_string<charT,ST,SA>::const_iterator,Allocator> &,const boost::basic_regex<charT,traits> &,boost::regex_constants::match_flag_type)' : could not deduce template argument for 'const std::basic_string<charT,ST,SA> &' from 'CString'
          c:\boost_1_50\boost\regex\v4\regex_search.hpp(76) : see declaration of 'boost::regex_search'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(128): error C2784: 'bool boost::regex_search(const std::basic_string<charT,ST,SA> &,boost::match_results<std::basic_string<charT,ST,SA>::const_iterator,Allocator> &,const boost::basic_regex<charT,traits> &,boost::regex_constants::match_flag_type)' : could not deduce template argument for 'const std::basic_string<charT,ST,SA> &' from 'CString'
          c:\boost_1_50\boost\regex\v4\regex_search.hpp(76) : see declaration of 'boost::regex_search'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(128): error C2784: 'bool boost::regex_search(const charT *,boost::match_results<const charT*,Allocator> &,const boost::basic_regex<charT,traits2> &,boost::regex_constants::match_flag_type)' : could not deduce template argument for 'const charT *' from 'CString'
          c:\boost_1_50\boost\regex\v4\regex_search.hpp(67) : see declaration of 'boost::regex_search'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(128): error C2780: 'bool boost::regex_search(BidiIterator,BidiIterator,boost::match_results<Iterator,Allocator> &,const boost::basic_regex<charT,traits> &,boost::regex_constants::match_flag_type,BidiIterator)' : expects 6 arguments - 3 provided
          c:\boost_1_50\boost\regex\v4\regex_search.hpp(46) : see declaration of 'boost::regex_search'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(128): error C2780: 'bool boost::regex_search(BidiIterator,BidiIterator,boost::match_results<Iterator,Allocator> &,const boost::basic_regex<charT,traits> &,boost::regex_constants::match_flag_type)' : expects 5 arguments - 3 provided
          c:\boost_1_50\boost\regex\v4\regex_search.hpp(37) : see declaration of 'boost::regex_search'
c:\documents and settings\user\мои документы\visual studio 2010\projects\httpclient\httpclient\httpclientdlg.cpp(130): error C2664: 'ATL::CStringT<BaseType,StringTraits>::CStringT(const VARIANT &)' : cannot convert parameter 1 from 'const boost::sub_match<BidiIterator>' to 'const VARIANT &'
          with
          [
              BaseType=wchar_t,
              StringTraits=StrTraitMFC<wchar_t>
          ]
          and
          [
              BidiIterator=std::_String_const_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>
          ]
          Reason: cannot convert from 'const boost::sub_match<BidiIterator>' to 'const VARIANT'
          with
          [
              BidiIterator=std::_String_const_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>
          ]
          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
А без "угадайки", не объясните в чём дело?
0
Ушел с форума
Эксперт С++
 Аватар для Убежденный
16481 / 7444 / 1187
Регистрация: 02.05.2013
Сообщений: 11,616
Записей в блоге: 1
09.06.2013, 13:48
Boost regex работает с std::string или std::wstring.
У Вас в функции используется CString, которая, кстати, еще непонятно
какого типа - ANSI или Unicode-версии. То есть, CStringA или CStringW.
Вместо того, чтобы выполнять "грубые" приведения одного к другому,
нужно попробовать что-то вроде такого:
C++
1
2
3
4
std::wstring Str = url.GetString();
regex_search(Str, host, re);
std::wstring Result = host[1];
return (CString(Result.c_str()));
Здесь нет приведений, поэтому если типы несовместимые,
например std::string и CStringW, будет предупреждения компилятора.

Добавлено через 54 секунды
Цитата Сообщение от artem78 Посмотреть сообщение
wregex re(L"^(?:http:\/\/)?([^\/]*)");
Кстати, в C и C++ необходимо экранировать обратный слэш:

C++
1
wregex re(L"^(?:http:\\/\\/)?([^\\/]*)");
1
 Аватар для artem78
6 / 8 / 2
Регистрация: 20.12.2012
Сообщений: 729
09.06.2013, 13:58  [ТС]
Цитата Сообщение от Убежденный Посмотреть сообщение
У Вас в функции используется CString, которая, кстати, еще непонятно
какого типа - ANSI или Unicode-версии
Юникод

Добавлено через 8 минут
Спасибо за объяснения, заработало.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
09.06.2013, 13:58
Помогаю со студенческими работами здесь

Ошибка преобразования
Вот мой код. В общем в конце выбивает &quot;error C2664: kasat: невозможно преобразовать параметр 5 из &quot;double (__cdecl...

Ошибка преобразования
Привет! Что-то вдруг случилось и теперь все переменные int записываются автоматически, как Int32. Хотелось бы вернуться к стандарту....

Ошибка преобразования типов
сразу после нажатия btn_matr выходит ошибка &quot; ''-не интеджер &quot; Form1: TForm1; n,i,j:byte; max:integer; ...

Ошибка преобразования формата
Выдает вот такую ошибку Error 1 error C2664: 'int CDC::GetTextFaceW(int,LPTSTR) const' : cannot convert parameter 2 from 'char ' to...

Ошибка преобразования формата
Выдает вот такую ошибку в строке 8.Как решить данную проблему? Error 8 error C2664: 'int CDC::GetTextFaceW(int,LPTSTR) const' : cannot...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
Первый деплой
lagorue 16.01.2026
Не спеша развернул своё 1ое приложение в kubernetes. А дальше мне интересно создать 1фронтэнд приложения и 2 бэкэнд приложения развернуть 2 деплоя в кубере получится 2 сервиса и что-бы они. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит токи на L и напряжения на C в установ. режимах до и. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru