國立屏東大學 資訊工程系 物件導向程式設計
turnin code cpp.hw1-1
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]$
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
[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 。