我是一个 C/C++ 初学者,试图构建一个看起来非常简单的程序:它将文件加载到 c 字符串 (const char*) 中。然而,虽然这个程序非常简单,但它并没有以我理解的方式工作。看一看:
#include <iostream>
#include <fstream>
std::string loadStringFromFile(const char* file)
{
std::ifstream shader_file(file, std::ifstream::in);
std::string str((std::istreambuf_iterator<char>(shader_file)), std::istreambuf_iterator<char>());
return str;
}
const char* loadCStringFromFile(const char* file)
{
std::ifstream shader_file(file, std::ifstream::in);
std::string str((std::istreambuf_iterator<char>(shader_file)), std::istreambuf_iterator<char>());
return str.c_str();
}
int main()
{
std::string hello = loadStringFromFile("hello.txt");
std::cout << "hello: " << hello.c_str() << std::endl;
const char* hello2 = loadCStringFromFile("hello.txt");
std::cout << "hello2: " << hello2 << std::endl;
hello2 = hello.c_str();
std::cout << "hello2 = hello.c_str(), hello2: " << hello2 << std::endl;
return 0;
}
输出如下所示:
hello: Heeeeyyyyyy
hello2: 青!
hello2 = hello, hello2: Heeeeyyyyyy
初始的 hello2 值每次都会改变,总是一些随机的汉字(我使用的是日本电脑,所以我猜这就是为什么它是汉字)。
在我天真的观点中,这两个值似乎应该打印相同。一个函数返回一个 c++ 字符串,然后我将其转换为 c 字符串,另一个函数加载该字符串,从该字符串转换 c 字符串并返回它。我通过在返回它之前计算值来确保字符串在 loadCStringFromFile 中正确加载,确实这是我的想法,例如:
/*(inside loadCStringFromFile)*/
const char* result = str.c_str();
std::cout << result << std::endl;//prints out "Heeeyyyyyy" as expected
return result;
那么为什么要改变价值呢?谢谢您的帮助...