首頁  >  文章  >  後端開發  >  將使用者輸入儲存到向量中時,為什麼只計算第一個數字?

將使用者輸入儲存到向量中時,為什麼只計算第一個數字?

Patricia Arquette
Patricia Arquette原創
2024-10-26 12:01:29512瀏覽

Why is only the first number being counted when storing user input into a vector?

將使用者輸入儲存到向量中:綜合指南

在此查詢中,使用者嘗試將多個數字輸入向量中,並且隨後使用函數呼叫對它們進行計數。下面提供的程式碼存在著僅計算第一個數字的問題:

<code class="cpp">template <typename T>
void write_vector(const vector<T>&amp; V)
{
   cout << "The numbers in the vector are: " << endl;
  for(int i=0; i < V.size(); i++)
    cout << V[i] << " ";
}

int main()
{
  int input;
  vector<int> V;
  cout << "Enter your numbers to be evaluated: " << endl;
  cin >> input;
  V.push_back(input);
  write_vector(V);
  return 0;
}</code>

罪魁禍首在於目前僅從使用者讀取單一整數。為了解決這個問題,需要一個循環。

<code class="cpp">while (cin >> input)
    V.push_back(input);</code>

此循環不斷從標準輸入中檢索整數,直到沒有更多可用的輸入。當 cin 偵測到檔案結尾 (EOF) 或遇到非整數值時,輸入過程結束。

或者,可以使用哨兵值,其缺點是阻止使用者輸入該特定值。例如:

<code class="cpp">while ((cin >> input) && input != 9999)
    V.push_back(input);</code>

在此場景中,將收集輸入,直到使用者輸入 9999(或觸發另一個使 cin 無效的條件),此時循環終止。

以上是將使用者輸入儲存到向量中時,為什麼只計算第一個數字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn