【小技巧】如何輸入未知長度的數組,用回車結束輸入


今天做了“去哪兒”的筆試,編程題並不難,但是卡在輸入數據上了,數據讀都讀不進來,很讓人惱火。

一般的題目輸入數據會是這樣:
第一行:一個整數n,表示數組長度 (6)
第二行:n個整數,之間用空格隔開  (1 4 1 1 5 6)

但是去哪兒的題目挺奇怪,輸入只有一行

第一行:輸入n個整數,以空格隔開 (1 3 4 6 7 8)

 

這樣帶來一個問題,讀取並存儲這些數據有一定的困難,我最開始是用while(cin>>a),但是這樣的問題在於程序並不以“回車”作為結束跳出循環,而是一直處在輸入數據的狀態,即便是我已經吧輸入的數據存入數組或者向量,程序依然是在處理輸入。后來我又想用getline()函數,但是這個函數把空格也當為一個字符讀入,這對於數據的存儲是一件很麻煩的事情;后來經過在網上查找資料,我注意到這個問題使用get()函數放入while循環中來處理是個不錯的辦法

 

下面這種情況是知道要輸入多少數據,比較好處理一些

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 int main()
 5 {
 6     int num;
 7     cin >> num;
 8  
 9     vector<int> vecNum;
10     int temp;
11     for (int i = 0; i < num; ++i)
12     {
13         cin >> temp;
14         vecNum.push_back(temp);
15     }
16  
17     for (vector<int>::iterator itr = vecNum.begin(); itr != vecNum.end(); ++itr)
18     {
19         cout << *itr << endl;
20     }
21  
22     return 0;
23 }

 

像下面這種情況就像我之前說的,一直會陷入while中,無法執行while后面的數據,這種情況適合需要輸入和處理的數據全部都在while中;示例如下,15、16行的數據根本執行不到,因為單步調試就會發現一直是在處理cin

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     int a;
 8     vector<int> v(100);
 9     while (cin >> a)
10     {
11         cout << -1 * a << endl;
12         v.push_back(a);
13         cout << a << endl;
14     }
15     cout << "hahah" << endl;
16     for (int i = 0; i < v.size(); i++)
17         cout << v[i] * 10 << endl;
18     return 0;
19 }

 

下面這種就是使用get()的方法,也是目前來說最好的方法,可以讀取長度未知的整數;當然也可以每次輸入的數據使用vector的push_back()方法,這樣就不用擔心會下標訪問越界,這樣的方式適合用在輸入不定長度的、以空格分隔、以回車結尾、后面還需需要進一步處理的數據

 1 #include<iostream>
 2 #include<string> 
 3 using namespace std;
 4 int main()
 5 {
 6 int arr[100];
 7 int temp;
 8 int count=0;
 9 char c;
10 while(((cin>>temp).get(c)))
11 {
12      
13     arr[count]=temp;
14     if(c=='\n')
15         break;
16     count++;
17     if(count>=100)
18         break;
19 }
20 for(int i=0;i<=count;i++)
21     cout<<arr[i];
22 system("pause");
23 return 0;
24  
25 }

 

參考資料:

https://bbs.csdn.net/topics/391821665

https://zhidao.baidu.com/question/1895481546423695740.html

https://blog.csdn.net/loveliuzz/article/details/73555058

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM