Essential C++--Exercise of Chpt.1
前言
本文用于记录阅读书籍《Essential C++》Chpt.1后完成课后习题。
正文(Exercise Code)
1.1 Hello World
将先前介绍的main()
程序依样画葫芦地输入。
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string name;
cout << "please input your name: ";
cin >> name;
cout << '\n'
<< "hello, "
<< name
<< "... and goodbye! \n";
return 0;
}
1.2 Hello World again
将string
头文件注释掉:
// #include <string>
#include <iostream>
//#include <string>
using namespace std;
int main(void)
{
string name;
cout << "please input your name: ";
cin >> name;
cout << '\n'
<< "hello, "
<< name
<< "... and goodbye! \n";
return 0;
}
1.3 See the world another way
将函数名main()
改为my_main()
,然后重新编译。有什么结果?
#include <iostream>
#include <string>
using namespace std;
int my_main(void)
{
string name;
cout << "please input your name: ";
cin >> name;
cout << '\n'
<< "hello, "
<< name
<< "... and goodbye! \n";
return 0;
}
1.4 Colorful World
试着扩充这个程序的内容:(1)要求用户同时输入名字(first name)和姓氏(last name)。(2)修改输出结果,同时打印姓氏和名字。
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string first_name, sec_name;
cout << "please input your first name: ";
cin >> first_name;
cout << "please input your second name: ";
cin >> sec_name;
cout << "hello, "
<< first_name
<< sec_name
<< "... and goodbye! \n";
return 0;
}
1.5 Hello to you
编写一个程序,能够询问用户的姓名,并读取用户所输入的内容。请确保用户输入的名称长度大于两个字符。如果用户的确输入了有效名称,就相应一些信息。
#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
using namespace std;
int get_another_try(int *bAnotherTry)
{
char input;
cout << "try it? (Y:yes, N:no): ";
cin >> input;
if ('y' == input || 'Y' == input)
{
*bAnotherTry = 1;
}
else if ('n' == input || 'N' == input)
{
*bAnotherTry = 0;
}
else
{
cout << "pls check your input, use y[Y] or n[N] \n";
return -1;
}
return 0;
}
int main(void)
{
const int type_num = 2; // type0 represent c-style, type_1 represent cpp-style
int bAnotherTry = 1; // if need another try
int ipt_type = 0; // user choose input type
// checker
if (ipt_type != 0 && ipt_type != 1)
{
cout << "invalid ipt type: " << ipt_type;
cout << '\n';
goto exit;
}
while(1 == bAnotherTry)
{
while(0 != get_another_try(&bAnotherTry))
{
continue;
}
switch (bAnotherTry)
{
case 1:
{
cout << "let's try it! \n";
break;
}
case 0:
{
cout << "user exit! \n";
continue;
}
default:
{
bAnotherTry = 0;
cout << "err! exit n";
continue;
}
}
cout << "pls input function type(0:c-style\t1:cpp-style): ";
cin >> ipt_type;
cout << "get input type: " << ipt_type;
cout << '\n';
if (0 == ipt_type)
{
char str[64] = {'\0'};
cout << "please input your name: ";
scanf("%s", str);
cout << '\n';
cout << "Now is type 0 \n";
if (strlen(str) < 2)
{
cout << "Oops, pls make sure your name longer than 2 characters! \n";
continue;
}
cout << "hello, " << str
<< "..., Bye! \n";
}
else if (1 == ipt_type)
{
string usr_name;
cout << "please input your name: ";
cin >> usr_name;
cout << '\n';
cout << "Now is type 1 \n";
if (usr_name.size() < 2)
{
cout << "Oops, pls make sure your name longer than 2 characters! \n";
continue;
}
cout << "hello, " << usr_name
<< "... Bye! \n";
}
else
{
cout << "do nothing! \n";
}
}
exit:
return 0;
}
1.6 Use tools
编写一个程序,从标准输入设备读取一串整数,并将读入的整数依次放到array及vector,然后遍历这两种容器,求取数据总和。将总和及平均值输出至标准输出设备。
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
using namespace std;
int main(void)
{
vector<int> v_store;
int a_store[64];
int a_store_idx = 0;
int i_tmp = 0;
int i_sum = 0;
cout << "pls input a list of int var: ";
while(cin >> i_tmp)
{
cout << "get i_tmp: " << i_tmp
<< '\n' << endl;
a_store[a_store_idx++] = i_tmp;
v_store.push_back(i_tmp);
if ('\n' == getchar())
{
cout << "get new line flag! \n" << endl;
break;
}
};
i_sum = 0;
// cal array sum var + avg var
for(int i = 0; i < a_store_idx; i++)
{
cout << "array: i[" << i << "], "
<< "val[" << a_store[i] << "] \n"
<< endl;
i_sum += a_store[i];
}
cout << "array: "
<< "get sum: " << i_sum << ", "
<< "avg: " << i_sum / a_store_idx
<< "\n" << endl;
i_sum = 0;
// cal vector sum var + avg var
for(int i = 0; i < v_store.size(); i++)
{
cout << "vector: i[" << i << "], "
<< "val[" << v_store.at(i) << "] \n"
<< endl;
i_sum += v_store.at(i);
}
cout << "vector: "
<< "get sum: " << i_sum << ", "
<< "avg: " << i_sum / v_store.size()
<< "\n" << endl;
return 0;
}
1.7 Iterator Algorithm
使用你最趁手的编辑工具,输入两行(或更多)文字并存盘。然后编写一个程序,打开该文本文件,将其中每个字都读取到一个vector<string>
对象中。遍历该vector
,将内容显示到cout
。然后利用泛型算法sort()
,对所有文字排序。
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <fstream>
#include <algorithm>
using namespace std;
#define IN_FILE_PATH ("./in_file.txt") /* input file */
#define OUT_FILE_PATH ("./out_file.txt") /* output file */
int pr_vector_info(vector<string> *v_str)
{
if (!v_str)
{
cout << "ptr null!" << endl;
return -1;
}
for(int i = 0; i < v_str->size(); i++)
{
cout << "vector: i[" << i << "], "
<< "string[" << v_str->at(i) << "]"
<< endl;
}
return 0;
}
int main(void)
{
int ret = 0;
ifstream in_file(IN_FILE_PATH);
if (!in_file)
{
cout << "open file: " << IN_FILE_PATH << " failed!" << endl;
return -1;//goto exit;
}
vector<string> v_str;
string str_tmp;
// get from in_file and store into vector
while(in_file >> str_tmp)
{
v_str.push_back(str_tmp);
}
cout << "before sorting!" << endl;
// print cout vector info before sorting
ret = pr_vector_info(&v_str);
if (ret)
{
cout << "pr vector failed!" << endl;
return -1;//goto exit;
}
// sort
sort(v_str.begin(), v_str.end());
cout << "after sorting!" << endl;
// print cout vector info after sorting
ret = pr_vector_info(&v_str);
if (ret)
{
cout << "pr vector failed!" << endl;
return -1;//goto exit;
}
// write new vector info into output file
ofstream out_file(OUT_FILE_PATH, ios_base :: app);
if (!out_file)
{
cout << "open out file: " << OUT_FILE_PATH << "failed" << endl;
return -1;
}
for(int i = 0; i < v_str.size(); i++)
{
out_file << v_str.at(i) << endl;
}
cout << "proc end!" << endl;
//exit:
return 0;
}
1.8 What a comforting world
1.4节的switch
语句让我们得以根据用户答错的次数提供不同的安慰语句。请以array
储存四种不同的字符串信息,并以用户答错次数作为array
的索引值,以此方式来显示安慰语句。
#include <iostream>
#include <string>
using namespace std;
bool get_another_try(void)
{
char c_input = 0;
bool bNeedTry = 0;
cout << "try it? (Y/y or N/n): ";
cin >> c_input;
cout << "get input: " << c_input << endl;
if ('Y' == c_input || 'y' == c_input)
{
bNeedTry = 1;
}
else
{
bNeedTry = 0;
if (('N' != c_input) && ('n' != c_input))
{
cout << "invalid input!" << endl;
}
}
return bNeedTry;
}
int simu_failure(void)
{
int i_rslt = 0;
cout << "pls input choice(1:success, 0:failure): ";
cin >> i_rslt;
return i_rslt;
}
int main(void)
{
int i_tmp_try_rslt = 0;
int i_try_num = 0;
int i_fail_num = 0;
bool bTry = 0;
char a_err_info[4][32] =
{
{"fail 1 time!"}, {"fail 2 times!"}, {"fail 3 times!"}, {"err too many cnt! try harder!"}
};
while(get_another_try() >> bTry)
{
i_try_num++;
// dbg: simulation of try
i_tmp_try_rslt = simu_failure();
// if success, continue
if (1 == i_tmp_try_rslt)
{
cout << "congrats!" << endl;
continue;
}
i_fail_num = (0 == i_tmp_try_rslt) ? i_fail_num+1 : i_fail_num;
switch(i_fail_num)
{
case 1:
case 2:
case 3:
{
cout << a_err_info[i_fail_num-1] << endl;
break;
}
default:
{
cout << a_err_info[3] << endl;
goto exit;
}
}
}
exit:
cout << "try[" << i_try_num << "], "
<< "fail[" << i_fail_num << "]" << endl;
return 0;
}
结语
个人阅读书籍《Essential C++》之余创建此专栏,用于记录完成每一章节后附录的exercise。如有问题,请各位不吝指正。