Board logo

標題: 字串處理 (六) - 取得字串長度 1 [打印本頁]

作者: 方浩葦    時間: 2024-10-5 13:42     標題: 字串處理 (六) - 取得字串長度 1

本帖最後由 方浩葦 於 2024-10-5 18:11 編輯

設計一程式, 能計算使用者輸入的字串長度(有幾個字元)

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     int sum=0;
  7.     char str[50];
  8.     cout<<"輸入一字串: ";
  9.     cin.getline(str,50);
  10.     for (int i = 0; str[i] != '\0'; i++)
  11.         sum++;
  12.     cout<<"本字串共包含: "<<sum<<" 個字元"<<endl;
  13.     system("pause");     
  14.     return 0;
  15. }
複製代碼

作者: 鄭豊翰    時間: 2024-11-30 10:14

  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4. using namespace std;

  5. int main() {
  6.     string str;
  7.     int sum=0;
  8.     cout << "輸入一字串: ";
  9.     getline(cin, str);
  10.     for (int i = 0; str[i] != '\0'; i++)
  11.         sum++;
  12.     cout<<"本字串共包含: "<<sum<<" 個字元"<<endl;
  13.     system("pause");
  14.     return 0;
  15. }
複製代碼

作者: 劉冠毅    時間: 2024-12-7 14:00

  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<string>
  4. #include <algorithm>
  5. using namespace std;
  6. int main()
  7. {
  8.     int sum=0;
  9.     char str[50];
  10.     cout<<"輸入字串: ";
  11.     cin.getline(str,50);
  12.     for(int i =0;str[i]!='\0';i++){
  13.         sum=sum+1;
  14.     }
  15.    
  16.     cout<<"此字串有 "<<sum<<"個字元"<<endl;
  17.     system("pause");
  18.     return 0;   
  19. }
複製代碼





歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://seed.istak.org.tw/) Powered by Discuz! 7.2