第10章は、入力ストリームと出力ストリームである。実務上は、エラー処理に関わる多くの部分がこの範疇に属するので重要な章なのだが、退屈な章であることも確かである。最後のところに、「ところで、実際にコードと説明をすべて読んだだろうか。それとも、ぼんやり眺めて読み飛ばしただろうか。」という問いかけがあって、笑ってしまった。確かに、きっちりと読みには、つらい章である。
練習問題11は、次の通り。
テキストファイルに含まれている整数をすべて合計するプログラムを作成する。これらの整数はホワイトスペースで区切られた情愛で含まれている。
基本的には、1文字読んで、読み戻し、読んだ1文字が数字なら数字として、読んだ1文字が数字以外なら文字列として読むという構造にした。読んだ1文字が'-'なら、マイナスとして取り扱うようにしている。私の回答は、下記の通り。
#include "..\..\std_lib_facilities.h"
int main(){
try {
cout << "ファイル名を入力してください:";
string iname;
cin >> iname;
ifstream ist{ iname };
if (!ist) error("指定されたファイルは開けませんでした", iname);int sum = 0;
while (true) {
char ch;ist >> ch;
if (ist.bad()) error("入力にエラーが発生しました");
if (ist.eof()) break;
if ((ch >= '0') && (ch <= '9')) {
ist.unget();
int n;
ist >> n;
sum += n;
} else if (ch=='-') {
ist >> ch;
if ((ch >= '0') && (ch <= '9')) {
ist.unget();
int n;
ist >> n;
sum -= n;
}
} else {
ist.unget();
string s;
ist >> s;
}
}cout << "合計は:" << sum << endl;
return 0;
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
char c;
while (cin >> c&& c != ';');
return 1;
}
catch (...) {
cerr << "exception\n";
char c;
while (cin >> c && c != ';');
return 2;
}}
模範解答http://www.stroustrup.com/Programming/Solutions/Ch10/e10-11.cppは、少し方針が異なる。文字のチェックなどを関数にしていて、確かにその方が見通しがいいと思う。’-‘の処理は方針が違うようだ。
コメント