Note that there are some explanatory texts on larger screens.

plurals
  1. POC strings vs const char* is confusing me... help please
    text
    copied!<p>I'm a C/C++ beginner trying to build what seems like a pretty simple program: it loads a file into a c-string (const char*). However, although the program is incredibly simple, it's not working in a way I understand. Take a look:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; std::string loadStringFromFile(const char* file) { std::ifstream shader_file(file, std::ifstream::in); std::string str((std::istreambuf_iterator&lt;char&gt;(shader_file)), std::istreambuf_iterator&lt;char&gt;()); return str; } const char* loadCStringFromFile(const char* file) { std::ifstream shader_file(file, std::ifstream::in); std::string str((std::istreambuf_iterator&lt;char&gt;(shader_file)), std::istreambuf_iterator&lt;char&gt;()); return str.c_str(); } int main() { std::string hello = loadStringFromFile("hello.txt"); std::cout &lt;&lt; "hello: " &lt;&lt; hello.c_str() &lt;&lt; std::endl; const char* hello2 = loadCStringFromFile("hello.txt"); std::cout &lt;&lt; "hello2: " &lt;&lt; hello2 &lt;&lt; std::endl; hello2 = hello.c_str(); std::cout &lt;&lt; "hello2 = hello.c_str(), hello2: " &lt;&lt; hello2 &lt;&lt; std::endl; return 0; } </code></pre> <p>The output looks like this:</p> <pre><code>hello: Heeeeyyyyyy hello2: 青! hello2 = hello, hello2: Heeeeyyyyyy </code></pre> <p>The initial hello2 value changes every time, always some random kanji (I'm using a Japanese computer, so I'm guessing that's why it's kanji).</p> <p>In my naive view, it seems like the two values should print identically. One function returns a c++ string, which I then convert to a c-string, and the other loads the string, converts the c-string from that and returns it. I made sure that the string was loading properly in loadCStringFromFile by couting the value before I returned it, and indeed it was what I had thought, e.g.:</p> <pre><code>/*(inside loadCStringFromFile)*/ const char* result = str.c_str(); std::cout &lt;&lt; result &lt;&lt; std::endl;//prints out "Heeeyyyyyy" as expected return result; </code></pre> <p>So why should the value change? Thanks for the help...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload