0
votes

Hi upon compiling this code in Visual studio 2008 i get the following error

#include<iostream>
#include<string>
using namespace std;
void main()
{
     basic_string<wchar_t> abc("hello world");
     cout<<abc;
     return;
}

error C2664: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string(std::basic_string<_Elem,_Traits,_Ax>::_Has_debug_it)' : cannot convert parameter 1 from 'const char [12]' to 'std::basic_string<_Elem,_Traits,_Ax>::_Has_debug_it'

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)

what is that i'm doing wrong?

Can any one help me understand the things happening behind? Thanks

3

3 Answers

3
votes

wchar_t specifies wide character types. By default a const char pointer to a literal string is not wide, but you can tell the compiler to treat it as a wide character array by prefixing it with 'L'.

So just change to

basic_string<wchar_t> abc(L"hello world");
3
votes

Try:

error C2664:

basic_string<wchar_t> abc(L"hello world");

error C2679:

cout << abc.c_str();

(Since the compiler cannot/will not provide a suitable overload for every user created type. However, since this is also a standard type i.e. wstring, I looked up the appropriate headers and found no suitable operator<< that takes either a string or a wstring.)

and use int main, so you have:

int main(void)
{        
     basic_string<wchar_t> abc(L"hello world");
     cout << abc.c_str() << endl;
     return 0;
}

Though, you really should be using std::wstring instead of reinventing the wheel.

2
votes

The problem is that you're mixing wide character and (narrow?) character types.

For your basic_string, use either:

// note the L"..." to make the literal wchar_t
basic_string<wchar_t> abc(L"hello world");  

// note that basic_string is no longer wchar_t
basic_string<char> abc("hello world");

or the equivalent:

// wstring is just a typedef for basic_string<wchar_t>
wstring abc(L"hello world");

// string is just a typedef for basic_string<char>
string abc("hello world");

And change the output to also match:

cout << abc;   // if abc is basic_string<char>

wcout << abc;  // if abc is basic_string<wchar_t>