【问题标题】:std::string Not Getting Terminated Properlystd::string 未正确终止
【发布时间】:2013-10-08 03:13:40
【问题描述】:

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

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,但也包括一些额外的字节垃圾。

【问题讨论】:

    标签: c++ string std outputstream fileoutputstream


    【解决方案1】:

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

    【讨论】:

    • 另外,很长一段时间都不需要调用.c_str() 到输出流。 logFile &lt;&lt; output; 工作正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    相关资源
    最近更新 更多