c++ - std::string 未正确终止

标签 c++ string std outputstream fileoutputstream

当我发送 std::string通过调用 ostream << string.c_str(); 到输出流字符串未正确终止。为什么是这样?

class Application {
public:
    bool print() {
        out << "Content-Type: text/html; charset=utf-8\r\n\r\n";
        std::ifstream inFileStream;
        inFileStream.open("./test.html");
        if(!inFileStream.is_open()) {
            out << "Error Opening File";
            return true;
        }
        boost::uintmax_t templateSize = boost::filesystem::file_size("./test.html");
        std::string output;
        char* templateData = new char[templateSize];
        char* bytePtr = templateData;
        inFileStream.read(templateData, templateSize);

        std::ofstream logFile;
        logFile.open("/tmp/test.log");
        while(*bytePtr != EOF) {
            if(*bytePtr ==  '{')
                readVar(&bytePtr, &output);
            else
                output.push_back(*bytePtr);

            bytePtr++;
        }
        delete[] templateData;
        output.push_back(0);
        logFile << output.c_str();
        return true;

    }
private:
    void readVar(char** bytePtrPtr, std::string* output) {
        while(**bytePtrPtr != EOF) {
            if(**bytePtrPtr == '}')
                return;
            output->push_back('*');
            (*bytePtrPtr)++;
        }
    }
};

的输出(在日志文件中) 包括正确解析的 test.html ,还有一些额外的字节垃圾。

最佳答案

读取的数据没有被EOF终止。您从位于文件末尾和转换为 EOF 的第一个 char 之间的文件中转储一些垃圾。一旦处理了 n 个字符,您应该停止向 output 添加字符的循环,其中 n 是调用 inFileStream.read 的结果(...)

关于c++ - std::string 未正确终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19125022/

相关文章:

c++ - 是否可以在 C++ 中查看命名空间的所有内容?

C++ std::string 到数字模板

c++ - 析构函数会破坏静态成员吗​​?

c++ - 使用 libmp4v2 和 OpenH264 将 h264 混合为 mp4

c++ - 在 OpenGL Win32 上激活多重采样

c - 按 C 顺序查找带元音的单词

java - 当字符串不可变时,为什么 System.out.println(s.concat ("some string"));返回改变后的值

Python:将字符串时间字典转换为日期时间

c++ - std::map 使用大量内存

c++ - 帮助我使这段代码异常安全