歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++編程練習-最長單詞

C++編程練習-最長單詞

日期:2017/3/1 11:16:41   编辑:Linux編程

Description
輸入一個英文句子,長度不超過200個字符。其中可包含的符號只有逗號","和句號"."。
輸出句子中最長的一個單詞。如果有多個這樣的單詞,輸出最後出現的。
Input
多組數據,每行為一個句子,其中符號"."不代表句子結束,譬如人名中可含有".”。
Output
每行一個最長單詞。這裡單詞的定義是僅由連續的字母組成的字符串。
Sample Input
Good morning.
Have a nice day.
Sample Output
morning
nice

參考代碼

  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4. int main(){
  5. int max;
  6. char s[210],p[210];
  7. char *pch;
  8. while(std::cin.getline(s,210)){
  9. max = 0;
  10. //divided into word
  11. pch = strtok(s,",. ");
  12. while(pch != NULL){
  13. if(strlen(pch) >= max){
  14. max = strlen(pch);
  15. strcpy(p,pch);
  16. }
  17. pch = strtok(NULL,",. ");
  18. }
  19. //print result
  20. std::cout<<p<<std::endl;
  21. }
  22. return 0;
  23. }
Copyright © Linux教程網 All Rights Reserved