C 语法通过变量和文本命名文件

C++ syntax to name file via variable and text

本文关键字:文本 文件 变量 语法      更新时间:2023-10-16

我有一个程序,该程序以文件的名称为参数(示例:books.txt),运行,然后将结果输出到新的文本文件中。我需要用附录命名输出文件(示例:books_output.txt)。

我尝试的方法是

ofstream outputFile;
outputFile.open(argv[1] + "_output.txt", 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);

您不能在2 C字符串之间放置A 。改用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);

读取更好但意思是同一件事