通过变量和文本命名文件的 C++ 语法
C++ syntax to name file via variable and text
我有一个程序将文件名作为参数(例如:books.txt),运行,然后将结果输出到一个新的文本文件。我需要用附录命名输出文件(例如:books_output.txt)。
我试过的方法是
ofstream outputFile;
outputFile.open(argv[1] + "_output.txt", ofstream::out);
但这没有编译。
我怎样才能完成这项工作?
不能在 2 个 C 字符串之间放置 +。请改用 std::string。这样做
ofstream outputFile;
std::string fname = std::string(argv[1]) + "_output.txt";
outputFile.open(fname.c_str(), ofstream::out);
更新的 c++ 版本允许
outputFile.open(fname, ofstream::out);
读起来更好,但意思相同
您的陈述应如下所示(如我评论中所述):
outputFile.open(std::string(argv[1]) + "_output.txt", ofstream::out);
// ^^^^^^^^^^^^ ^
假定 argv[1]
来自标准 main()
签名
int main(int argc, char* argv[])
argv[1]
是一个 char*
指针,您不能以这种方式连接 char*
指针。
由于有些人担心过时的 C++ 标准版本的支持,早期版本的 std::ofstream::open()
签名不直接支持 const std::string
参数,而只支持 const char*
。如果你有这种情况,你的陈述应该是这样的
outputFile.open((std::string(argv[1]) + "_output.txt").c_str(), ofstream::out);
我有一个程序将文件名作为参数(例如:books.txt),运行,然后将结果输出到一个新的文本文件。我需要用附录命名输出文件(例如:books_output.txt)。
我试过的方法是
ofstream outputFile;
outputFile.open(argv[1] + "_output.txt", ofstream::out);
但这没有编译。 我怎样才能完成这项工作?
不能在 2 个 C 字符串之间放置 +。请改用 std::string。这样做
ofstream outputFile;
std::string fname = std::string(argv[1]) + "_output.txt";
outputFile.open(fname.c_str(), ofstream::out);
更新的 c++ 版本允许
outputFile.open(fname, ofstream::out);
读起来更好,但意思相同
您的陈述应如下所示(如我评论中所述):
outputFile.open(std::string(argv[1]) + "_output.txt", ofstream::out);
// ^^^^^^^^^^^^ ^
假定 argv[1]
来自标准 main()
签名
int main(int argc, char* argv[])
argv[1]
是一个 char*
指针,您不能以这种方式连接 char*
指针。
由于有些人担心过时的 C++ 标准版本的支持,早期版本的 std::ofstream::open()
签名不直接支持 const std::string
参数,而只支持 const char*
。如果你有这种情况,你的陈述应该是这样的
outputFile.open((std::string(argv[1]) + "_output.txt").c_str(), ofstream::out);