注册 登录
编程论坛 C++教室

[求助]如何在system中引用变量

黄鹏宇 发布于 2020-01-30 10:41, 2970 次点击
如何使用system中添加一个变量,例如:
system("copy con 你想要的文件名.txt");
其中你想要的文件名是一个变量。
10 回复
#2
纯蓝之刃2020-01-30 13:40
你可以先把字符串分解成不同的字符串,然后使用sprintf把字符串连起来。
char name[50];
    char name1[50]="你想要的文件名";
    sprintf(name,"copy con %s.txt",name1);
    system(name);
#3
黄鹏宇2020-01-30 14:52
回复 2楼 纯蓝之刃
麻烦再详细一些,变量名是a
#4
纯蓝之刃2020-01-30 15:30
程序代码:
#include<iostream>
using namespace std;

int main()
{
    string name1="a";        //你想要的文件名
    string name="copy con .txt";//共用的字符串
    name.insert(9,name1);    //将你想要的文件名插入到共用的字符串
    system(name.c_str());    //得到c语言格式的字符串
   
//cout<<name<<endl;
    return 0;
}
#5
黄鹏宇2020-01-31 15:20
回复 4楼 纯蓝之刃
我是想让输入一个名称,再以这个名称作为txt命名
#6
黄鹏宇2020-01-31 15:33
回复 4楼 纯蓝之刃
就好象这样:
 string x;
 cin>>x;
 system("copy con x.txt");//其中x是一个变量
#7
雪影辰风2020-02-01 13:20
你可以定义一个string然后进行拼接,如下:
程序代码:

string fileName;
cin>>fileName;
string cmd="copy con ";
cmd+=fileName;
cmd+=".txt";
system(cmd);

我写MFC的时候就是这么拼接的,Visual Studio 2017检查挺严格的,应该可以,只不过这做法有点傻瓜式,你可以去搜搜其他做法
希望以上内容对你有帮助,感谢阅读!
#8
黄鹏宇2020-02-01 16:22
回复 7楼 雪影辰风
但仿佛不可以
#9
黄鹏宇2020-02-01 16:24
回复 7楼 雪影辰风
错误:[Error] cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int system(const char*)'
#10
雪影辰风2020-02-01 17:58
回复 9楼 黄鹏宇
程序代码:

char fileName[10001];
cin>>fileName;
char cmd[10001];
sprintf(cmd,"Copy con %s.txt",fileName);
system(cmd);

我改了一下,编译是通过了,至于实际效果我不太知道,不行再告诉我
#11
雪影辰风2020-02-01 18:07
哦对了,sprintf头文件是cstdio
1