std::string 未正确终止
std::string Not Getting Terminated Properly
当我通过调用ostream << string.c_str();
将std::string
发送到输出流时,字符串未正确终止。这是为什么呢?
class Application {
public:
bool print() {
out << "Content-Type: text/html; charset=utf-8rnrn";
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(...)
的结果。
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- cppcheck在const std::string[]上引发警告
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 将std::string传递给WriteConsole API
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- llvm构建器向基本块添加终止符
- string ::容量/储备()计数终止null
- 在哪里使用 c++(即 std::string) 字符串以及在哪里使用'