I have a pipe-delimited string that I want to put into the vector named result
. However, it won't compile on getline
. If I remove the pipe-delimiter character in getline
, then it compiles:
#include <sstream>
using namespace std;
wstringstream ss(L"1,2,3|4,5,6|7,8,9|");
vector<wstring> result;
wstring substr;
while (ss.good())
{
getline(ss, substr, '|'); // <- this does not compile with wchar_t
result.push_back(substr);
}
How do I use getline
with an incoming wchar_t
string? I could do WideCharToMultiByte
but that's a lot of processing if I can use getline
with a wchar_t
.
Your code does not compile because getline
requires that the delimiter and the stream use the same character type. Your string stream ss
uses wchar_t
, but '|'
is evaluated by the compiler as a char
.
The solution is to use the appropriate character literal, like this:
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
wstringstream ss(L"1,2,3|4,5,6|7,8,9|");
wstring substr;
while (ss.good())
{
getline(ss, substr, L'|');
std::wcout << substr << std::endl;
}
}