21

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 incompatible with parameter of type const char_t *

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

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.

What am I doing wrong here?

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

4
  • 1
    Did you #include <sstream>? Your code with the stringstream should work. Commented Apr 19, 2014 at 2:55
  • Please try to convert string using int ConvertedInteger = _wtoi(OrigWString);... Commented Apr 19, 2014 at 4:30
  • You could always construct a std::string from the string and use std::stoi on that. You might incur a memory allocation if the number is big enough, but I doubt it's any worse than using stringstreams. Commented Apr 19, 2014 at 4:41
  • also I think #include <istream> is required for wistringstream Commented Apr 19, 2014 at 5:39

2 Answers 2

51

No need to revert to C api (atoi), or non portable API (_wtoi), or complex solution (wstringstream) because there are already simple, standard APIs to do this kind of conversion : std::stoi and std::to_wstring.

#include <string> std::wstring ws = L"456"; int i = std::stoi(ws); // convert to int std::wstring ws2 = std::to_wstring(i); // and back to wstring 
Sign up to request clarification or add additional context in comments.

1 Comment

One reason to avoid using sto*() functions family is because they all throw exceptions. ato*() don't
-1

you can use available API from wstring.h.

to convert WString to int try int ConvertedInteger = _wtoi(OrigWString);.

for reference use msdn.microsoft.com/en-us/library/aa273408(v=vs.60).aspx.

3 Comments

What do you mean by stream returns the string values? The OP's code works, the error is elsewhere.
@Praetorian I mean that when we write/ read data to/ from stream object it works on string values in OP case it is wstring
The OP is using wistringstream which deals with wchar_ts, not chars. Once again, his code works, look at the link in my previous comment. The error message about using an incomplete type most likely means he forgot to include some header file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.