2017年10月20日 星期五

[C_AR209-中] 兵聖(C++)

[C_AR209-中] 兵聖

問題描述 :
克勞塞維茲是西方的兵聖,他曾經說過:「聰明但不勤快,適合當將軍;聰明又勤快,適合當參謀;不聰明但又不勤快,適合當阿兵;不聰明但勤快,就抓去槍斃!」試根據此些原則來設計條件式判斷之程式。(以1代表聰明,2代表不聰明,3代表勤快,4代表不勤快,幫助兵聖判斷適合擔任的職務)
輸入說明 :
第一列會有一個數字n(1~20)代表英文字串之筆數,接下來會有n筆姓名及聰明與否及勤快與否之測試資料,每筆一列。
輸出說明 :
對於每筆輸入姓名及聰明與否及勤快與否之測試資料,並依序輸出適合當將軍(General)、當參謀(Staff)、當阿兵(Soldier),或就抓去槍斃(execute by shooting)的結果。
範例 :

輸入範例輸出範例
5
Aaron 1 3
Denny 1 3
David 2 3
Hank 2 4
Jack 1 4
Aaron Staff
Denny Staff
David execute by shooting
Hank Soldier
Jack General


  1. #include <iostream>  
  2. #include <string.h>  
  3. #include <sstream>  
  4. #include <vector>     
  5. using namespace std;  
  6.   
  7. int main() {  
  8.     // [C_AR209-中] 兵聖  
  9.     vector<string>arr;   //設一維陣列arr  
  10.     string input;     
  11.     int n;  
  12.     cin >> n;  
  13.     n = n + 1;  
  14.     //字串input , token  
  15.     string token;  
  16.     int c=0;    //用來記錄放的陣列位置,每空白放一個,從arr[0]開始  
  17.     for(int i = 0;i < n;i++)  
  18.     {  
  19.         getline(cin,input);  
  20.         //使用者輸入 ex:how are you, 注意只有讀一行  
  21.         istringstream delim(input);               
  22.         //將打好的東西放到字串delim裡,包含空白  
  23.         while(getline(delim,token,' ')) 
  24.         //getline(delim[來源位置],token[存入位置],' '[分割的條件])  
  25.         {  
  26.             arr.push_back(token);  //ex:  arr[0] = token ="how"  
  27.             c++;                   //換arr[1]  
  28.         }  
  29.     }  
  30.           
  31.     for(int j=0;j<c;j++) //印出來  
  32.     {     
  33.         if(j%3 == 0)  
  34.         {  
  35.             cout << arr[j] << " " ;   //輸出人名
  36.         }  
  37.         if(j % 3 == 1)   //輸出
  38.         {  
  39.             if(arr[j] == "1" && arr[j+1] == "4")  
  40.             {  
  41.                 cout << "General" << endl;   
  42.             }  
  43.             if(arr[j] == "1" && arr[j+1] == "3")  
  44.             {  
  45.                 cout << "Staff" << endl;   
  46.             }  
  47.             if(arr[j] == "2" && arr[j+1] == "4")  
  48.             {  
  49.                 cout << "Soldier" << endl;   
  50.             }  
  51.             if(arr[j] == "2" && arr[j+1] == "3")  
  52.             {  
  53.                 cout << "execute by shooting" << endl;   
  54.             }  
  55.         } 
  56.     }  
  57.     c = 0;  //歸零
  58. }  

沒有留言:

張貼留言