如何在重命名函数 (c++) 中使用变量?

How do I use variables in the rename funciton (c++)?

本文关键字:变量 c++ 重命名 函数      更新时间:2023-10-16

我正在尝试使用重命名功能让用户名将文件从一个文件夹移动到另一个文件夹,这是我的代码:

string c;
cout<<"What file should be moved?"<<endl;
getline(cin,c);
char oldname[] = "D:\subasta\"+ c +".txt";
char newname[] = "D:\subasta\open\"+ c +".txt";

问题是我不能使用变量字符串 c。 还有其他选择吗?

两个版本:

#include <cstdio> // std::rename
#include <string>
int main() {
std::string c;
std::string oldname = "D:\subasta\"+ c +".txt";
std::string newname = "D:\subasta\open\" + c + ".txt";
std::rename(oldname.c_str(), newname.c_str());
}
#include <filesystem> // std::filesystem::rename
#include <string>
int main() {
std::string c;
std::string oldname = "D:\subasta\"+ c +".txt";
std::string newname = "D:\subasta\open\" + c + ".txt";
std::filesystem::rename(oldname, newname);
}

试着这样写。

string c;         //your original string
char variable[];  //your convert variable
strcpy(variable, c.c_str());
cout<<"What file should be moved?"<<endl;
getline(cin,c);
char oldname[] = "D:\subasta\"+ variable +".txt";
char newname[] = "D:\subasta\open\"+ variable +".txt";