iT邦幫忙

0

如何在c++的system( ) 函式中放入變數

不明 2021-07-28 21:50:012640 瀏覽
  • 分享至 

  • xImage

最近想要使用c++ system() 函式來開啟使用者輸入進來的字串檔名,原本以為只要system("./"+filename)就好了,請問有沒有解法。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
EN
iT邦好手 1 級 ‧ 2021-07-28 22:24:03

建議發問前先嘗試 Google 一下,這個答案蠻好找的(?)


// https://www.796t.com/post/NXQ3MWk=.html

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    cout<<"name the app u want to open";

    string app;
    cin>>app;

    const string cmd = "start " + app;

    system(cmd.c_str()); // <-- Use the .c_str() method to convert to a c-string.
    return 0;
}
不明 檢舉

感謝

0
CWKSC
iT邦新手 4 級 ‧ 2021-07-30 15:11:59

可以用 sprintf

https://www.cplusplus.com/reference/cstdio/sprintf/

#include <cstdio>

int main() {
   char command[128];
   char fileName = "meow.txt";

   sprintf(command, "./%s", fileName);
   system(command);
   
   return 0;
}
0
JamesDoge
iT邦高手 1 級 ‧ 2023-02-14 09:24:39

您可以使用C++中的字串串接符號 "+" 來將字串合併,然後再將合併後的字串傳遞給 system() 函式。以下是一個簡單的範例程式碼:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string filename;
    cout << "請輸入檔案名稱:";
    cin >> filename;

    string command = "./" + filename;  // 將"./"和filename合併成一個字串
    system(command.c_str());  // 將合併後的字串轉換為C-style字串傳給system()函式

    return 0;
}

我要發表回答

立即登入回答