如何将wstringstream和getline与wchar_t一起使用



我有一个管道分隔的字符串,我想把它放入名为result的向量中。但是,它不会在getline上编译。如果我删除getline中的管道分隔符,那么它将编译:

#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);
}

如何将getline与传入的wchar_t字符串一起使用?我可以做WideCharToMultiByte,但如果我可以将getlinewchar_t一起使用,那就需要大量的处理。

由于getline要求分隔符和流使用相同的字符类型,因此您的代码不会编译。字符串流ss使用wchar_t,但编译器会将'|'计算为char

解决方案是使用适当的文字字符,如以下所示:

#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;
}
}

最新更新