如何在 C++ 中等待使用者輸入
 
本文將介紹等待使用者輸入的 C++ 方法。需要注意的是,下面的教程假設使用者輸入的內容與程式執行無關。
使用 cin.get() 方法等待使用者輸入
    
get() 是 std:cin 成員函式,它的工作原理類似於 >> 輸入運算子,從流中提取字元。在這種情況下,當我們對處理使用者輸入不感興趣,只需要實現等待功能時,我們可以呼叫 get 函式而不需要任何引數。不過請注意,當按下 Enter 鍵時,這個函式就會返回。
#include <iostream>
#include <vector>
using std::cin;
using std::copy;
using std::cout;
using std::endl;
using std::vector;
int main() {
  vector<char> arr = {'w', 'x', 'y', 'z'};
  int flag;
  flag = cin.get();
  for (auto const& value : arr) cout << value << "; ";
  cout << "\nDone !" << endl;
  return EXIT_SUCCESS;
}
輸出:
w; x; y; z;
Done !
使用 getchar 函式來等待使用者的輸入
getchar 函式是 C 標準庫函式,用於從輸入流(stdin)中讀取一個字元。與前一個函式一樣,這個方法期望返回一個新的行字元(即按下 Enter 鍵)。getchar 在出錯時或遇到流的末端時返回 eof。
#include <iostream>
#include <vector>
using std::cin;
using std::copy;
using std::cout;
using std::endl;
using std::vector;
int main() {
  vector<char> arr = {'w', 'x', 'y', 'z'};
  int flag;
  flag = getchar();
  for (auto const& value : arr) cout << value << "; ";
  cout << "\nDone !" << endl;
  return EXIT_SUCCESS;
}
使用 getc 函式等待使用者輸入
    
作為一種替代方法,我們可以用 getc 函式代替上面的例子。getc 傳遞的是 FILE *stream 引數,用於從任何給定的輸入流中讀取,但在本例中,我們傳遞的是 stdin,這是通常與終端輸入相關的標準輸入流。當 Enter 鍵被按下時,這個函式也會返回。
#include <iostream>
#include <vector>
using std::cin;
using std::copy;
using std::cout;
using std::endl;
using std::vector;
int main() {
  vector<char> arr = {'w', 'x', 'y', 'z'};
  int flag;
  flag = getchar();
  for (auto const& value : arr) cout << value << "; ";
  cout << "\nDone !" << endl;
  return EXIT_SUCCESS;
}
避免使用 system("pause") 來等待使用者輸入
system 函式用於執行 shell 命令,命令名稱以字串文字形式傳遞。因此,如果傳遞一個 pause 作為引數,就會嘗試執行相應的命令,這只有在 Windows 平臺上才有。比起使用 system("pause") 這種不可移植的方式,最好用上面列出的方法實現一個自定義的 wait 函式。
#include <iostream>
#include <vector>
using std::cin;
using std::copy;
using std::cout;
using std::endl;
using std::vector;
int main() {
  vector<char> arr = {'w', 'x', 'y', 'z'};
  int flag;
  system("pause");
  for (auto const& value : arr) cout << value << "; ";
  cout << "\nDone !" << endl;
  return EXIT_SUCCESS;
}
輸出:
sh: 1: pause: not found
w; x; y; z;
Done !
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
