[英]how does the function system() work in c++?
我試圖理解使用system(“some command”)在c ++中進行的系統調用。 這是代碼
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
cout << "Hello ";
system("./pause");
cout << "World";
cout << endl;
return 0;
}
可執行文件“pause”是從以下代碼創建的
#include <iostream>
using namespace std;
int main()
{
cout<<"enter any key to continue\n";
cin.get();
return 0;
}
我得到以下輸出
enter any key to continue
1
Hello World
有人可以向我解釋輸出嗎? 我在期待這個 -
Hello
enter any key to continue
1
World
您觀察到的特定行為的原因似乎只是cout
緩沖: Hello
不會立即打印,而是保存在緩沖區中直到輸出endl
(或緩沖區完全填充,或者您顯式調用flush()
)。 這與system()
調用無關。
一個更簡單的例子:
cout << "Hello";
sleep(10);
cout << "World";
兩個單詞將同時出現,而不是延遲10秒。
它可能不是系統調用的情況,而是輸出流緩沖。
cout << "xxx"
不需要輸出內容,因此system
調用的程序可以在cout
將緩沖區刷新到控制台之前執行。
嘗試在cout << "Hello"
之后添加cout.flush()
或者寫cout << "Hello" << flush
另外: cout << endl
自動調用flush
system
在shell中運行命令。 但你的問題不是system
而是cout
。 cout
是行緩沖的,即。 它將不會刷新(寫出)其數據,直到遇到新的行字符。 你需要用cout << flush
明確地刷新它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.