目錄表

國立屏東大學 資訊工程系 物件導向程式設計

Turnin 作業1


第1題

turnin code cpp.hw1-1

  1. 設計一個名為lexico.cpp的程式
  2. 讓使用者輸入一個整數n,以決定其後將輸入的字串數目
  3. 使用迴圈讓使用者輸入n個英文字串
  4. 每個字串皆不超過20個字元,使用Enter結束每一次的輸入,字串內容全部為大寫或小寫字母,並可包含空白字元
  5. 將這n個字串中的大寫字母都轉換為小寫字母,再依Lexicographical order(也就是字典順序)輸出
  6. 你必須要以動態字串陣列來實作,其宣告必須為:

   int n;
   cout << "How many strings do you want to input? ";
   cin >> n;
 
   char **str = new char * [n];
   ...
   for(int i=0;i<n;i++)
   {
      ...
      str[i] = new char[21];
      ...
   }
   ...

你可能須要載入「#include <string>」或「#include <cstring>」等相關的標頭檔

程式執行結果參考如下:

[02:16 junwu@ws hw1]$ ./a.out
How many strings do you want to input? 5
Input 1: Willemite
Input 2: Subject
Input 3: sub rosa
Input 4: Birth Date
Input 5: subJeCtS
 
Lexicographical Ordering...
 
birth date
sub rosa
subject
subjects
willemite
[02:16 junwu@ws hw1]$ 

第2題

turnin code cpp.hw1-2

考慮以下兩個C++標頭檔:

#define LenFN 20
#define LenLN 10
 
#ifndef STRUCT_NAME
#define STRUCT_NAME
 
struct Name
{
  char firstname[LenFN+1];
  char lastname[LenLN+1];
};
 
Name *setName(const char *name);
 
#endif

#include "name.h"
 
char *initial(Name *n);

以及下面這個main1.cpp程式:

using namespace std; 
#include <iostream>  
#include <cstring>   
#include "name.h"
#include "initial.h"
 
int main()
{
  Name *someone = new Name;
  char *name = new char[LenFN+LenLN+1];
 
  cout << "Please input your name: ";
  for(int i=0;i<(LenFN+LenLN);i++)
    cout << "_";
  for(int i=0;i<(LenFN+LenLN);i++)
    cout << "\b";
 
  cin.getline(name, LenFN+LenLN);
 
  someone = setName(name);
 
  cout << "Your first name is " << someone->firstname << "." << endl;
  cout << "Your last name is " << someone->lastname << "." << endl;
  cout << "The initial of your name is " << initial(someone) << endl;
 
  return 0;
}

using namespace std;
#include <iostream>
#include <cstring>
#include <string>
#include "name.h"
 
Name *setName(const char *name)
{
  Name *somebody = new Name;
 
   ...
 
  return somebody;
}

至於initial.cpp則是負責initial()函式的實作,用以接收一個Name的結構體,並傳回一個字串:

注意:你只須turnin 「name.cpp」與「initial.cpp」這兩個程式!我們會使用以下的方式,編譯你的程式:

g++ -c name.cpp
g++ -c initial.cpp 
g++ main1.cpp name.o initial.o

  1. 程式執行結果參考:

[02:16 junwu@ws hw1]$ ./a.out 
Please input your name: Yo-Yo Ma______________________
Your first name is Yo-Yo.
Your last name is Ma.
The initial of your name is Ma, Y.-Y.
[02:16 junwu@ws hw1]$ ./a.out
Please input your name: Wu, Jun________________________
Your first name is Jun.
Your last name is Wu.
The initial of your name is Wu, J.
[02:16 junwu@ws hw1]$ 

本題所需之檔案,可至ws.csie.nptu.edu.tw上取得,其所在目錄為/home/stu/public/cpp2020/hw1-2 。