我有一个管道分隔的字符串,我想把它放入名为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
,但如果我可以将getline
与wchar_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;
}
}