【问题标题】:Convert char array to CString in c++在 C++ 中将 char 数组转换为 CString
【发布时间】:2020-10-14 18:12:45
【问题描述】:

我无法将 char * 转换为 CString.. 最后 2 行打印什么也不打印...我需要它作为 cstring 的一部分才能将其传递给函数..

char result[500];
strcpy(result, "\\\\.\\pipe\\");                    
strcat(result, a["BLOB"][i].GetString());// just appending to "result" a string I am reading from json file..
CString  temp(result);
printf("\n1-The pipeName we are looking at is %s \n", result);
printf("\n2-The pipeName we are looking at is %s \n", temp);
printf("\n3-The pipeName we are looking at is %s \n", CString(result,500));

【问题讨论】:

  • 什么是CString,它来自哪里?它不是标准 C++ 的一部分。
  • CString.GetString() 之间,我假设这是指WinAPI,并添加了标签......一个完整的例子(包含)会有澄清了这一点。
  • @DevSolar 可能是this,在mfc,而不是winapi
  • @TanveerBadar:好的...我来自 Amiga,然后从那里直接进入 Linux,所以微软的一切对我来说都是“WinAPI”。 :-D 随意重新标记。
  • 是的@DevSolar 这是您提供的链接。

标签: c++ winapi c-strings strcat


【解决方案1】:

printf 很粗糙。将%sprintf 一起使用将假定您传递给它的第一个指针大小的字节实际上是一个指向字符串的指针(又名char*)。

CString 可能是这样,也可能不是。在你的情况下,它似乎不是。

要使用 printf,您需要这样做:

printf("\n2-The pipeName we are looking at is %s \n", temp.GetString());

或者干脆停止使用printf 并使用具有更高类型安全性的东西,例如cout

【讨论】:

    【解决方案2】:

    将字符串直接构建到CString,并在打印时使用内置转换为const char *

    CString  temp("\\\\.\\pipe\\");
    temp += a["BLOB"][i].GetString(); // or: temp.Format("\\\\.\\pipe\\%s", a["BLOB"][i].GetString());
    printf("-The pipeName we are looking at is %s\n", (const char *)temp);
    

    【讨论】:

    • 我们传递的格式参数不正确..有什么建议吗?
    • @ccoding 错误指向的确切代码行是什么?另外,你没有说 a["BLOB"][i].GetString() 返回什么类型,但如果它 not const char * 那么你可能需要添加一个演员表。
    【解决方案3】:

    printf() 怎么知道CString 是什么?什么是类?如何将CString转换为c风格的字符串?

    这是按预期工作的。

    基于 MFC/WFC 也提供 CString 的假设,您要查找的内容可能已记录在 here

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 1970-01-01
      • 2012-11-07
      • 2015-08-07
      • 2010-10-25
      • 2015-05-14
      • 1970-01-01
      • 2011-07-26
      相关资源
      最近更新 更多