Mar*_* L. 4 c++ file-io wchar-t stream
我在使用基于模板的文件读取程序时遇到问题,例如:
bool parse(basic_ifstream<T> &file)
{
T ch;
locale loc = file.getloc();
basic_string<T> buf;
file.unsetf(ios_base::skipws);
if (file.is_open())
{
while (file >> ch)
{
if(isalnum(ch, loc))
{
buf += ch;
}
else if(!buf.empty())
{
addWord(buf);
buf.clear();
}
}
if(!buf.empty())
{
addWord(buf);
}
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
这将在我实例化这个类时有效<char>,但在我使用时<wchar_t>(显然)有问题.
课外,我正在使用:
for (iter = mp.begin(); iter != mp.end(); ++iter )
{
cout << iter->first << setw(textwidth - iter->first.length() + 1);
cout << " " << iter->second << endl;
}
Run Code Online (Sandbox Code Playgroud)
要写入此数据结构中的所有信息(它是a map<basic_string<T>, int>),并且如预测的那样,如果iter->first不是char数组,则cout会爆炸.
我已经在网上找到了共识是使用wcout,但不幸的是,因为这个程序要求在编译时可以更改模板(<char>- > <wchar_t>)我不知道如何只需选择cout或wcout即可.也就是说,除非有办法在不改变大量代码的情况下读/写宽字符.
如果这个解释听起来很复杂,请告诉我,我会尽我所能解决.
使用特质类.相反,在代码中直接引用COUT的,你会引用traits<T>::cout,然后专门traits<char>到std :: cout和traits<wchar_t>到wcout.
更新
template <typename T>
class traits {
public:
static std::basic_ostream<T>& tout;
};
template<>
std::ostream& traits<char>::tout = std::cout;
template<>
std::wostream& traits<wchar_t>::tout = std::wcout;
int _tmain(int argc, _TCHAR* argv[])
{
traits<char>::tout<<"Ascii";
traits<wchar_t>::tout<<L"Unicode";
return 0;
}
Run Code Online (Sandbox Code Playgroud)