以下是具有输出文件的代码。如果我想每次都给这个输出文件不同的名称,即根据用户的要求,该怎么办。什么样的 getline 命令会有所帮助。我知道我可以简单地将字符串名称my_file但所需的名称在输入中而不是在字符串名称中。
void save(cdStruct *ptr) //Function that saves database info to file
{
ofstream dataFile;
dataFile.open("output.txt", ios::out | ios::app);
dataFile << ptr->title << endl;
dataFile << ptr->artist << endl;
dataFile << ptr->numberOfSongs << endl;
dataFile << ptr->number << endl;
dataFile.close();
}
您要更改此行:
dataFile.open("output.txt", ios::out | ios::app);
到这样的东西??
dataFile.open(my_name_string, ios::out | ios::app);
如果是,您只需要在之前读取此字符串,添加".txt"即可
。检查此代码:
字符串名称;
辛>姓名;name.append(".txt");
流数据文件;
dataFile.open(name.c_str(), ios::out | ios::app);
dataFile.close();
从您对其他答案的评论来看,听起来您正在将文件名作为std::string
传递给std::ofstream::open
。在C++11
之前,它只接受const char *
参数,不接受std::string
(请参阅此参考)。
要解决此问题,请使用filename.c_str()
作为第一个参数,而不是filename
。这将返回一个以 null 结尾的 char 数组,即 std::ofstream::open
您的错误消息告诉以下内容:您在应该使用char const *
的某个时候正在使用std::string
。现在我们只需要找到发生错误的适当位置。
快速浏览std::getline
的在线文档告诉我们,此功能不是问题:签名允许std::string
。唯一改变的是 std::ofstream(filename, std::ios::out | std::ios::ate)
,所以我们检查std::ofstream
的文档;确实是一个char const *
.
这个问题应该通过更换来快速解决
std::ofstream dataFile(filename, std::ios::out | std::ios::ate);
跟
std::ofstream dataFile(filename.data(), std::ios::out | std::ios::ate);
然后它应该编译。
尝试了解编译器为您提供的错误消息并搜索问题可能所在的引用非常重要。
您的具体问题不是"根据用户需要的输出文件提供所需的名称",而是"如何在命令行程序中读取用户输入"。为此,您可以使用std::getline
:
#include <iostream>
#include <string>
int main() {
std::string filename;
getline(std::cin, filename);
}
人们可能会试图使用operator<<
重载,
#include <iostream>
#include <string>
int main () {
std::string filename;
std::cin >> filename;
}
但是,如果您的文件名包含空格字符,它们会给出错误的结果。
旁注:当您想要强制实施非空值时,不要传递可为空的指针:
// don't: void save(cdStruct *ptr)
void save(cdStruct const &ptr) // <- ah, better