#include<iostream>#include<stdlib.h>// for rand(),srand()#include<ctime>// for time#include"string1.h"constint ArSize =10;constint MaxLen =81;intmain(){usingnamespace std;
String name;
cout <<"hi, what's your name?\n>> ";
cin >> name;
cout << name <<", please enter up to "<< ArSize
<<" short sayings <empty line to quit>:\n";
String sayings[ArSize];char temp[MaxLen];int i;for(i =0; i < ArSize; i++){
cout << i +1<<": ";
cin.get(temp, MaxLen);while(cin and cin.get()!='\n')continue;if(!cin || temp[0]=='\0')break;else sayings[i]= temp;}int total = i;if(total >0){
cout <<"here are your sayings:\n";// use pointers to keep track of shortest// first strings
String* shortest =&sayings[0];
String* first =&sayings[0];for(i =1; i < total; i++){if(sayings[i].length()< shortest->length()){
shortest =&sayings[i];}if(sayings[i]<*first){
first =&sayings[i];}}
cout <<"shortest saying:\n";
cout <<*shortest << endl;
cout <<"first alphabetically:\n"<<*first << endl;srand(time(0));int choice =rand()% total;// pick index at random// use new to create, initialize new string object
String* favorite =newString(sayings[choice]);
cout <<"my favorite saying:\n"<<*favorite << endl;delete favorite;}else{
cout <<"not much to say, eh?\n";}
cout <<"bye.\n";return0;}
4. 结果
hi, what's your name?
>> hablee
hablee, please enter up to 10 short sayings <empty line to quit>:
1: yuki and hablee
2: hablee and yuki
3: what's wrong with their relationship?
4:
here are your sayings:
shortest saying:
yuki and hablee
first alphabetically:
hablee and yuki
my favorite saying:
what's wrong with their relationship?
bye.
E:\projectFiles\CPPcodes\learn_cpp\DynamicMemory002\x64\Release\DynamicMemory002.exe (进程 39596)已退出,代码为 0。
按任意键关闭此窗口. . .