c++ - 如何在 C++11 中将 u32string 转换为 int?

标签 c++ string c++11 localization type-conversion

我们如何在 C++11 中将 u32string 转换为 int

另外,我应该使用什么方法将此类字符串的一部分转换为 int - 让开始和结束迭代器可用?

我试过:

u32string test=U"14";
cout << atoi(test.c_str());

但它抛出:

candidate function not viable: no known conversion from 'const char32_t *' to 'const char *' for 1st argument
extern int atoi (__const char *__nptr)

最佳答案

#include <locale>   // wstring_convert
#include <codecvt>  // codecvt_utf8
#include <iostream> // cout
#include <string>   // stoi and u32string

int main() {
  std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;

  std::u32string str = U"14";
  std::cout << std::stoi(convert.to_bytes(str));
}

这取决于 UTF-8 和使用相同数字表示法的“C”语言环境。


GCC 的标准库实现 libstdc++ 还不包括 codecvt 头文件或 std::wstring_convert。 libc++ 确实包括这两者,Visual Studio 的标准库实现也是如此。如果您必须使用 libstdc++,您可能会发现自己实现一个简单的转换函数最简单。

#include <algorithm> // transform
#include <iterator>  // begin, end, and back_inserter

std::string u32_to_ascii(std::u32string const &s) {
  std::string out;
  std::transform(begin(s), end(s), back_inserter(out), [](char32_t c) {
    return c < 128 ? static_cast<char>(c) : '?';
  });
  return out;
}

int u32toi(std::u32string const &s) { return stoi(u32_to_ascii(s)); }

关于c++ - 如何在 C++11 中将 u32string 转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16593775/

相关文章:

c++ - #define Glib::string std:wstring

C# 如何将大的 HEX 字符串转换为二进制

python - 在 Python 中解码双重编码的 utf8

java - 查找加起来等于给定字符串的所有子字符串组合

c++ - "cout"没有命名类型错误

c++ - condition_variable 等待参数?

.net - 不依赖 .net 的 Windows 安装项目

c++ - 为什么隐藏符号仍然添加到 DSO

c++ - eclipse 火星 : Symbol 'unique_ptr' could not be resolved

c++ - 我应该在这里使用什么样的指针?