【问题标题】:c++ c_str adding strange characters to the end of the stringc ++ c_str在字符串末尾添加奇怪的字符
【发布时间】:2012-04-19 12:13:51
【问题描述】:

首先让我感谢您抽出宝贵时间阅读本文。

我正在尝试用 C++ 读取文件。目前我有一个方法允许用户在资源管理器中选择一个文件并将其作为“std::string”返回。然后我必须打开这个文件,但我为此使用的方法使用 const char*。因此,我需要从一种转换为另一种。

如果 Windows 中有一种简单的方法可以使用字符串读取文件,请告诉我,因为它可以解决我的整个问题。

当我使用 str.c_str() 从字符串转换为 const char* 时,最后会得到很多奇怪的字符。我已经研究了具有相同问题的其他主题,但是对于这些项目,答案似乎都非常具体,或者说只是坚持使用 sting/vector。显然我很乐意这样做,但我没有使用字符串/向量打开文件的方法。

感谢任何帮助 :) 发生这种情况的代码和输出粘贴在下面。

*来源

std::string f;

               if (LOWORD(wParam) == 1) {

                       f = openFile();

                       char *fchar = new char[f.size()+1]; // +1 to account for \0 byte

                       //char *fchar = std::vector[1];

                       std::strncpy(fchar, f.c_str(), f.size());

                       file1 = fchar;

                       std::cout<<"string size: " << f.size() << std::endl;
                       std::cout<<"string: " << f << std::endl;
                       std::cout<<"fchar: " << fchar << std::endl;
                       std::cout<<"file1: " << file1 << std::endl;
               }

输出

 string size: 33
 string: C:\Users\Joseph\Pictures\back_raw
 fchar: C:\Users\Joseph\Pictures\back_raw═²²²²½½½½½½½½¯■
 file1: C:\Users\Joseph\Pictures\back_raw═²²²²½½½½½½½½¯■**

【问题讨论】:

    标签: string char character c-str


    【解决方案1】:

    std::strncpy() 不在字符串末尾放置 `\0' 字符。见http://www.cplusplus.com/reference/clibrary/cstring/strncpy/。你也需要复制它:

    std::strncpy(fchar, f.c_str(), f.size() + 1);

    【讨论】:

    • 谢谢!这就是问题所在:)
    【解决方案2】:

    file1 在哪里声明? 那么 openFile 呢? (想知道它的返回类型)

    您可以尝试手动输入 '\0' 吗?恕我直言,您的 char* 最后只是缺少 \0 ...

    【讨论】:

      【解决方案3】:

      确保在末尾添加\0,无论您需要什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-25
        • 1970-01-01
        • 1970-01-01
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        • 2011-09-16
        • 1970-01-01
        相关资源
        最近更新 更多