• 文章
  • 使用 cin 獲取使用者輸入。
作者:
2008 年 12 月 2 日(最後更新:2009 年 2 月 10 日)

使用 cin 獲取使用者輸入。

評分:3.7/5(83 票)
*****
不斷出現關於同一問題的提問。我如何使用 `>>` 從 `cin` 獲取使用者輸入到 X 型別。使用 `>>` 運算子會帶來很多問題。試著輸入一些無效資料,看看它是如何處理的。

`cin` 在導致輸入問題方面臭名昭著,因為它不會從流中刪除換行符,也不會進行型別檢查。因此,任何使用 cin >> var; 並接著使用另一個 cin >> stringtype;getline(); 的人都會收到空輸入。最佳實踐是不要混合使用 `cin` 的不同型別的輸入方法。

我知道使用 cin >> integer; 比下面的程式碼更容易。但是,下面的程式碼是型別安全的,如果你輸入了非整數內容,它會進行處理。上面的程式碼只會進入無限迴圈,並在你的應用程式中導致未定義的行為。

使用 cin >> stringvar; 的另一個缺點是 `cin` 不會進行長度檢查,並且會在遇到空格時停止。所以,如果你輸入的內容超過一個單詞,只有第一個單詞會被載入。空格和後面的單詞仍然留在輸入流中。

一個更優雅、更易於使用的解決方案是 getline(); 函式。下面的示例展示瞭如何載入資訊以及如何在型別之間進行轉換。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

 string input = "";

 // How to get a string/sentence with spaces
 cout << "Please enter a valid sentence (with spaces):\n>";
 getline(cin, input);
 cout << "You entered: " << input << endl << endl;

 // How to get a number.
 int myNumber = 0;

 while (true) {
   cout << "Please enter a valid number: ";
   getline(cin, input);

   // This code converts from string to number safely.
   stringstream myStream(input);
   if (myStream >> myNumber)
     break;
   cout << "Invalid number, please try again" << endl;
 }
 cout << "You entered: " << myNumber << endl << endl;

 // How to get a single char.
 char myChar  = {0};

 while (true) {
   cout << "Please enter 1 char: ";
   getline(cin, input);

   if (input.length() == 1) {
     myChar = input[0];
     break;
   }

   cout << "Invalid character, please try again" << endl;
 }
 cout << "You entered: " << myChar << endl << endl;

 cout << "All done. And without using the >> operator" << endl;

 return 0;
}