如何在 C++ 中暫停程式
本文將介紹幾種在 C++ 中暫停程式的方法。
使用 getc()
函式來暫停程式
getc()
函式來自 C 標準輸入輸出庫,它從給定的輸入流中讀取下一個字元。輸入流的型別為 FILE*
,該函式期望該流會被開啟。在幾乎所有的 Unix 系統中,在程式啟動過程中,有 3 個標準的檔案流被開啟-即:stdin
、stdout
和 stderr
。在下面的例子中,我們傳遞 stdin
作為引數,它對應一個控制檯輸入,以等待使用者繼續執行程式。
#include <iostream>
#include <thread>
#include <chrono>
using std::cout;
using std::endl;
using std::copy;
using std::this_thread::sleep_for;
using namespace std::chrono_literals;
int main()
{
int flag;
cout << "Program is paused !\n" <<
"Press Enter to continue\n";
// pause the program until user input
flag = getc(stdin);
cout << "\nContinuing .";
sleep_for(300ms);
cout << ".";
cout << ".";
cout << ".";
cout << "\nProgram finished with success code!";
return EXIT_SUCCESS;
}
輸出:
Program is paused !
Press Enter to continue
Continuing ....
Program finished with success code!
使用 std::cin::get()
方法來暫停程式
暫停程式的另一種方法是呼叫 std::cin
內建方法 get
,該方法從輸入流中提取引數指定的字元。在這種情況下,我們是讀取一個字元,然後將控制權返回給正在執行的程式。
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
using std::cout; using std::cin;
using std::endl; using std::vector;
using std::copy;
using std::this_thread::sleep_for;
using namespace std::chrono_literals;
int main()
{
int flag;
cout << "Program is paused !\n" <<
"Press Enter to continue\n";
// pause the program until user input
flag = cin.get();
cout << "\nContinuing .";
sleep_for(300ms);
cout << ".";
cout << ".";
cout << ".";
cout << "\nProgram finished with success code!";
return EXIT_SUCCESS;
}
使用 getchar()
函式來暫停程式的執行
作為另一種方法,我們可以用 getchar
函式呼叫重新實現同樣的功能。getchar
相當於呼叫 getc(stdin)
,它從控制檯輸入流中讀取下一個字元。
請注意,這兩個函式都可能返回 EOF
,表示已到達檔案末尾,即沒有可讀的字元。程式設計師負責處理任何特殊的控制流和返回的錯誤程式碼。
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
using std::cout; using std::cin;
using std::endl; using std::vector;
using std::copy;
using std::this_thread::sleep_for;
using namespace std::chrono_literals;
int main()
{
int flag;
cout << "Program is paused !\n" <<
"Press Enter to continue\n";
// pause the program until user input
flag = getchar();
cout << "\nContinuing .";
sleep_for(300ms);
cout << ".";
cout << ".";
cout << ".";
cout << "\nProgram finished with success code!";
return EXIT_SUCCESS;
}
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn