简体   繁体   English

C ++ c_str不返回整个字符串

[英]C++ c_str doesn't return entire string

I've tried the following code with both normal ifstreams and the current boost:iostream I'm using, both have the same result. 我已经尝试了以下代码与正常的ifstreams和当前的boost:iostream我正在使用,两者都有相同的结果。

It is intended to load a file from physfs into memory then pass it to a handler to process (eg Image, audio or data). 它旨在将文件从physfs加载到内存中,然后将其传递给处理程序进行处理(例如图像,音频或数据)。 Currently when c_str is called it only returns a small part of the file. 目前,当调用c_str时,它只返回文件的一小部分。

        PhysFS::FileStream file("Resources/test.png" , PhysFS::OM_READ);

    if(file.is_open()) {

        String* theFile;

        theFile = new String((std::istreambuf_iterator<char>(file)), 
        std::istreambuf_iterator<char>());

        String::iterator it;
        for ( it=theFile->begin() ; it < theFile->end(); it++ ) {
            std::cout << *it; 
        } // Outputs the entire file

        std::cout << theFile->c_str(); // Outputs only the first few lines

    }

The iterator loop outputs the entire png file as expected, but the c_str call only returns the first few characters (\\211PNG). 迭代器循环按预期输出整个png文件,但c_str调用仅返回前几个字符(\\ _ 211PNG)。

I've been trying variations of this code for quite some time with no success. 我一直在尝试使用此代码的变体很长一段时间没有成功。 Any ideas? 有任何想法吗?

I imagine that the next character is a null (ASCII 0) byte. 我想下一个字符是一个空(ASCII 0)字节。 c_str() simply gives you a *char, therefore your write to stdout is interpreted as a class C string which ends at the first null byte. c_str()只是给你一个* char,因此你对stdout的写入被解释为一个C类字符串,它以第一个空字节结束。

If you really need a C-like interface to this string, the main thing is that theFile->c_str() points to your data and theFile.length gives you the number of characters in the string. 如果你真的需要一个类似C语言的接口,那么主要的是theFile-> c_str()指向你的数据,而theFile.length给你字符串中的字符数。 So you might want to do something like this: 所以你可能想做这样的事情:

char *c_value = theFile->c_str()
for (int i = 0; i < theFile.length; i++)
{
   cout << c_value[i];
}

The real solution depends on why you are converting to a char * in the first place. 真正的解决方案取决于您首先转换为char *的原因。 If you are calling a legacy function that only accepts char *, there is likely also a length argument to that legacy function. 如果要调用仅接受char *的遗留函数,则该遗留函数可能还有一个长度参数。

其中一个字节可能是0.这意味着在传递char *时,字符串结尾为cout(c_str为)

I would consider using std::vector<unsigned char> instead of std::string for this. 我会考虑使用std::vector<unsigned char>而不是std::string It is a lot easier to deal with binary data in a vector. 在向量中处理二进制数据要容易得多。 You can reference the underlying pointer using &vec[0] if you need access to a C-style array. 如果需要访问C风格的数组,可以使用&vec[0]引用基础指针。 I would also make sure that your file abstraction use std::ios_base::binary for the file mode under the hood as well. 我还要确保你的文件抽象使用std::ios_base::binary作为引擎盖下的文件模式。

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

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