简体   繁体   English

如何在C ++中使用字符的ascii代码创建std :: wstring?

[英]How to create a std::wstring using the ascii codes of characters in C++?

I need to create a wstring with the chars that have the following ascii values: 30, 29, 28, 27, 26, 25. 我需要使用具有以下ascii值的字符创建wstring:30、29、28、27、26、25。

In VB6, I would do asc(30) + asc(29)+ etc... 在VB6中,我会执行asc(30)+ asc(29)+等等...

What's the C++ equivalent? 什么是C ++等效项?

Thanks! 谢谢!

Is this a trick question about character set conversion? 这是关于字符集转换的技巧问题吗? :) Because the standard does not guarantee that an ASCII character is represented by its ASCII integer value in a wchar_t (even though for most compilers/systems, this will be true). :)因为该标准不保证wchar_t中的ASCII整数值表示ASCII字符(即使对于大多数编译器/系统,也是如此)。 If it matters, explicitly widen your char using an appropriate locale: 如果很重要,请使用适当的语言环境显式扩展您的字符:

std::wstring s;
std::locale loc("C"); // pick a locale with ASCII encoding

s.push_back(std::use_facet<std::ctype<wchar_t> >(loc).widen(30));
s.push_back(std::use_facet<std::ctype<wchar_t> >(loc).widen(29));
s.push_back(std::use_facet<std::ctype<wchar_t> >(loc).widen(28));

Don't terminate with a trailing 0, it is added when you convert the wstring to a wchar_t * by invoking .c_str() 不要以尾随0结尾,当您通过调用.c_str()将wstring转换为wchar_t *时添加

An std::wstring is nothing more than an std::vector disguised as a string. std :: wstring只不过是伪装成字符串的std :: vector。

Therefore you should be able to use the push_back method, like this: 因此,您应该能够使用push_back方法,如下所示:

std::wstring s;

s.push_back(65);
s.push_back(0);

std::wcout << s << std::endl;

Don't forget the 0-terminator ! 不要忘记0终止符!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM