c++ - 从 std::string 和 std::wstring 获取 char 整数值

标签 c++ winapi unicode unicode-string

我试图通过在 C++ WinAPI 中将每个字母的 int 值相加来将字符串转换为数字。所以在 ASCII 中; std::string "AA"等于 130 (65+65)

字符串可以是 std::string 或 std::wstring。

为什么无论我输入什么字母,下面的函数总是返回零值?它不应该返回字母的 ASCII 或 Unicode 整数值吗?

printf("TEST a: %d \n", _tstoi(_T("a")));
printf("TEST A: %d \n", _tstoi(_T("A")));
printf("TEST b: %d \n", _tstoi(_T("b")));

我的 VC++ 应用程序目前使用 Unicode,并且前面的代码为每个字母打印出零。我记得听说 Unicode 与 ASCII 字符串有很大不同,除了 Unicode 有一个大约 30,000 长的字符库而 ASCII 是 256(我认为?)之外,你能弄清楚究竟有什么不同吗?

最佳答案

msdn 文章说:

"The input string is a sequence of characters that can be interpreted as a numerical value of the specified type. The function stops reading the input string at the first character that it cannot recognize as part of a number."

如果您使用包含实际数字的 unicode 字符串测试代码,您将看到正确的输出:

printf("TEST 1: %d \n", _tstoi(_T("1")));

输出:

TEST 1: 1

正如@Ylisar 所说,*toi 函数用于将数字值从字符串转换为整数变量。

以下代码将输出数字表示,但要注意常量变量的指针表示。我保留了两个版本,这样您就可以看到区别:

  printf("TEST 1: %d \n", _tstoi(_T("1")));
  printf("TEST a: %d \n", _tstoi(_T("a")));
  WCHAR* b(_T("b"));
  printf("TEST A: %d \n", _T("A"));
  printf("TEST b: %d \n", *b);

输出:

TEST 1: 1
TEST a: 0
TEST A: 13457492
TEST b: 98

查看更多信息 http://msdn.microsoft.com/en-us/library/yd5xkb5c%28v=vs.80%29.aspx

如果您想求和(累加)这些值,我建议您查看 STL 范围函数,它对此类事情有奇效。例如

#include <numeric>
#include <string>

printf("TEST a: %d \n", *_T("a")); // 97
printf("TEST b: %d \n", *_T("b")); // 98

wstring uString(_T("ba"));
int result = accumulate(uString.begin(), uString.end(), 0);
printf("TEST accumulated: %d \n", result);

结果:

TEST a: 97
TEST b: 98
TEST accumulated: 195

这样您就不必让 for 循环遍历所有值。范围函数真的很适合这样的事情。

查看更多信息:http://www.sgi.com/tech/stl/accumulate.html

关于c++ - 从 std::string 和 std::wstring 获取 char 整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7833665/

相关文章:

c# - 从 C# 中列出非 .NET DLL 函数

html - Unicode 字符对齐

c++ - 绘制许多四边形

c++ - 为什么 C++ 不能用偏移量推断数组大小?

c++ - 为什么输入迭代器在递增后会使其自身失效?

c++ - 是否可以打印对象的名称?

java - 使用上下文菜单捕获 HWND

c# - 如何在托管代码中创建 Windows 安全描述符?

python - 从字符串中取出一个 Unicode 字符并对其进行解码

c++ - 如何使用 STL 字符串和流读取/存储 unicode