返回列表 發帖

怎樣抓取空白分隔的數字(未知數目)?

範例輸入:
2 6 0 8 14 0 0 0 10 0 4 0 0

範例輸出:
2 6 0 8 14 0 0 0 10 0 4 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. string raw;
  4. int n;
  5. stringstream ss;
  6. vector<int> data;

  7. int main()
  8. {
  9.     cin.tie(0);
  10.     cin.sync_with_stdio(0);

  11.     getline(cin, raw);

  12.     ss<<raw;

  13.     while(ss>>n)
  14.         data.push_back(n);

  15.     for(int i: data)
  16.         cout<<i<<" ";
  17.     cout<<endl;

  18.     return 0;
  19. }

  20. /*
  21. 2 6 0 8 14 0 0 0 10 0 4 0 0
  22. */
複製代碼
以下為錯誤方式(要依題目規定輸入才可以,不能自己輸入-1):
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int n;
  4. int main()
  5. {
  6.     cin.tie(0);
  7.     cin.sync_with_stdio(0);

  8.     while(cin>>n){
  9.         if(n==-1)
  10.             break;
  11.         cout<<n<<" ";
  12.     }

  13.     return 0;
  14. }

  15. /*
  16. 2 6 0 8 14 0 0 0 10 0 4 0 0
  17. */
複製代碼
May

返回列表