我刚刚做了看似的事情新手常见的错误 https://stackoverflow.com/questions/721129/spot-the-error-in-this-file-reading-code-c:
首先我们读到许多教程之一 http://www.learncpp.com/cpp-tutorial/136-basic-file-io/事情是这样的:
#include <fstream>
int main() {
using namespace std;
ifstream inf("file.txt");
// (...)
}
其次,我们尝试在代码中使用类似的东西,如下所示:
#include <fstream>
int main() {
using namespace std;
std::string file = "file.txt"; // Or get the name of the file
// from a function that returns std::string.
ifstream inf(file);
// (...)
}
第三,新手开发人员对一些神秘的编译器错误消息感到困惑。
问题是ifstream http://www.cplusplus.com/reference/iostream/ifstream/ifstream/ takes const * char
作为构造函数参数。
The solution https://stackoverflow.com/questions/347949/convert-stdstring-to-const-char-or-char is to 将 std::string 转换为 const * char http://www.cplusplus.com/reference/string/string/c_str/.
现在,真正的问题是,对于新手来说,几乎所有教程中给出的“file.txt”或类似示例看起来都非常像 std::string。
那么,“我的文本”是 std::string、c 字符串还是 *char,还是取决于上下文?
您能否举例说明如何根据上下文对“我的文本”进行不同的解释?
[编辑:我认为上面的例子已经很明显了,但我应该更明确:我的意思是用双引号括起来的任何字符串的类型,即“myfilename.txt”,而不是该词的含义'细绳'。]
Thanks.