《C++ Primer》第五版课后习题解答_第五章(4)(20-25)
系统环境: windows 10 1703
编译环境:Visual studio 2017
5.20
#include <iostream> #include <string> using std::cout; using std::endl; using std::cin; using std::string; int main() { string str, temp; cout << "Please enter strings: " << endl; while (cin >> str) { if (temp == str) { cout << "Repeat!!! " << str << endl; break; } else { temp = str; } } if (cin.eof()) // 这里用了一个 cin.eof 表达式来判断输入的是否为文件尾 { cout << "No Repeat!!!" << endl; } return 0; }需要注意的是,当 while 循环结束后(无论是读取到末尾或是被 break 语句打断),如果不加判断语句就直接输出“无重复”,则此句一定会被输出。因此必须在循环外添加判断语句,以确定此刻的输入是否为文件尾。上述程序中使用了表达式 cin.eof()。当输入为文件尾时,该表达式返回 1。
5.21
#include <iostream> #include <string> using std::cout; using std::endl; using std::cin; using std::string; int main() { string str, temp; cout << "Please enter strings: " << endl; while (cin >> str) { if (temp == str) { if (isupper(str[0])) //判断输入的 string 的开头是否为大写 { cout << "Repeat!!! " << str << endl; break; } else //如果不是大写,则继续循环 { continue; } } else { temp = str; } } if (cin.eof()) // 这里用了一个 cin.eof 表达式来判断输入的是否为文件尾 { cout << "No Repeat!!!" << endl; } return 0; }
5.22
for (int sz = get_size(); sz <= 0; sz = get.size()) { ; }
5.23
#include <iostream> using std::cout; using std::cin; using std::endl; int main() { int i = 0, j = 0, k = 0; cout << "Enter two numbers:" << endl; cin >> i >> j; k = i / j; cout << k << endl; return 0; }
5.24
#include <iostream> using std::cout; using std::cin; using std::endl; using std::runtime_error; int main() { int i = 0, j = 0, k = 0; cout << "Enter two numbers:" << endl; cin >> i >> j; try { if (j == 0) { throw runtime_error("Your second number can't be zero!!!"); } k = i / j; cout << k << endl; } return 0; }输出为 error C2317 : 在行“12”上开始的“try”块没有 catch 处理程序。
5.25
#include <iostream> using std::cout; using std::cin; using std::endl; using std::runtime_error; int main() { float i = 0, j = 0, k = 0; cout << "Enter two numbers:" << endl; while (cin >> i >> j) { try { if (j == 0) { throw runtime_error("Your second number can't be zero!!!"); } k = i / j; cout << k << endl; break; } catch (runtime_error err) { cout << err.what() << "\n" << "do you want to start over? enter \"Y\" or \"N\"" << endl; char c; cin >> c; if (!cin || c == 'N') { break; } } } return 0; }