[C++] สอบถามวิธีใช้คำสั่ง system

กระทู้คำถาม
ของเดิมเป็นแบบนี้
t1 = "8.8.8.8";
x = system("ping -c1 -s1 8.8.8.8 > /dev/null 2>U1");
 รันได้ปกติ แต่อยากได้แบบนี้
t1 = "8.8.8.8";
x = system("ping -c1 -s1 " + t1 + " > /dev/null 2>U1");
แต่มันรันไม่ผ่าน ต้องทำไงครับ

[Spoil] คลิกเพื่อดูข้อความที่ซ่อนไว้
แก้ไขข้อความเมื่อ
คำตอบที่ได้รับเลือกจากเจ้าของกระทู้
ความคิดเห็นที่ 3
1. c++20 format โดยใช้ <format> แต่มีแค่ llvm clang++ และ msvc cl ที่มีใช้แล้ว  ส่วน gnu g++ ต้องคอมไพล์ fmt.dev เองไปก่อน
   auto cmd = format("ping -c1 -s1 {} > /dev/null 2>U1", t1);
   if (system(cmd.c_str() ) == 0) {

2.  ใช้ string::operator+()
   auto cmd = "ping -c1 -s1 " + t1 + " > /dev/null 2>U1";
   if (system(cmd.c_str() ) == 0) {

string.c_str() คืนค่า const char * ไปยัง null-terminated c string บน heap
ซึ่งต้องใช้สำหรับใส่ลงใน system
784 | extern int system (const char *__command) __wur;

[LIVE]
แสดงความคิดเห็น
โปรดศึกษาและยอมรับนโยบายข้อมูลส่วนบุคคลก่อนเริ่มใช้งาน อ่านเพิ่มเติมได้ที่นี่