Converting a std::wstring to int...

Hello,

I presume this to be very simple but I cannot get it to work.

I am simply trying to convert a std::wstring to an int.

I have tried two methods so far.

The first is to use the "C" method with "atoi" like so:

 
  int ConvertedInteger = atoi(OrigWString.c_str());


However, VC++ 2013 tells me:

Error, argument of type "const wchar_t *" is incompatable with parameter of type "const char_t *"

So my second method was to use this, per Google search:

1
2
3
4
5
6
7
std::wistringstream win(L"10");
			int ConvertedInteger;
			if (win >> ConvertedInteger && win.eof())
			{
				// The eof ensures all stream was processed and
				// prevents acccepting "10abc" as valid ints.
			}		


However VC++ 2013 tells me this:

"Error: incomplete type not allowed."

when using std::wistringstream win

What am I doing wrong here?

Is there a better way to convert a std::wstring to int and back?

Thank you for your time.
Last edited on
Could you post a full but small program that generates that error?
Sure, I can whip something up.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

int main()
{
    const std::wstring strings[] = {  L"12345", L"12345xyz", L"xyz12345", L"123456789012345" } ;
    
    for( auto& wstr : strings ) try
    {
        std::wcout << L"\n'" << wstr << L"' => " ;
        std::size_t pos = 0 ;
        int number = std::stoi( wstr, &pos ) ;
        std::wcout << L"converted to integer " << number << L'\n' ;
        if( pos < wstr.size() ) std::wcout << "    the first " << pos << L" characters were converted\n" ; 
    }
    catch( const std::invalid_argument& ) { std::wcerr << L"no conversion could be performed\n" ; }
    catch( const std::out_of_range& ) { std::wcerr << L"converted value would be out of the range of an int\n" ; }
}

'12345' => converted to integer 12345

'12345xyz' => converted to integer 12345
    the first 5 characters were converted

'xyz12345' => no conversion could be performed

'123456789012345' => converted value would be out of the range of an int

http://coliru.stacked-crooked.com/a/2649cc3d5c2618f8



> "Error: incomplete type not allowed."
> when using std::wistringstream win

#include <sstream>
Thank you very much for the example, I definitely tried to search but I didn't put in the right search text.
Topic archived. No new replies allowed.