c ++
prime演習8.11 :このセクションのプログラムは、外側のwhileループでisringstreamオブジェクトを定義します。レコードオブジェクトがループの外側で定義されている場合、プログラムにどのような変更を加える必要がありますか?再プログラムし、レコードの定義をwhileループの外に移動し、想定している変更方法が正しいことを確認しますか?
(おそらく、argv []を読み取ってファイルを取得し、getlineを使用して各行を読み取り、isringstreamを使用して各単語を抽出することを意味します)
(私が以下で始めたプログラム)
vector<string>v;
string temp;
for(auto p=argv+1;p!=argv+argc;++p){
ifstream input(*p);
if(input){
while(getline(input,temp)/*input>>temp*/){
// v.push_back(temp);
istringstream recod(temp);
string s;
// cout<<temp<<endl;
while(recod>>s){
// cout<<s<<endl;
v.push_back(s);
}
}
}else
cerr<<" could not open:"+string(*p);
}
for (auto &str : v)
{
cout<<str<<endl;
}
次の図は、変更されたプログラムを示しています。
タイトルの意味によると、recodは外部に記載されていますが、なぜ答えが間違っているのですか?
すべての行を読む必要がありますが、1行の数語しか読んでいません!!!
vector<string>v;
string temp;
istringstream recod;
for(auto p=argv+1;p!=argv+argc;++p){
ifstream input(*p);
if(input){
while(getline(input,temp)/*input>>temp*/){
// v.push_back(temp);
recod.str(temp);
string s;
// cout<<temp<<endl;
while(recod>>s){
// cout<<s<<endl;
v.push_back(s);
}
}
}else
cerr<<" could not open:"+string(*p);
}
for (auto &str : v)
{
cout<<str<<endl;
}
間違った理由:isringstreamストリームは、読み取りの最後にeofbitとfailbitを設定します。現時点では、isringstreamストリームを使用した読み取りに失敗します。
解決策:isringstreamストリームのclear()メンバー関数を呼び出し、リセットして復元します。
以下はもう1行です
vector<string>v;
string temp;
istringstream recod;
for(auto p=argv+1;p!=argv+argc;++p){
ifstream input(*p);
if(input){
while(getline(input,temp)/*input>>temp*/){
// v.push_back(temp);
recod.clear();
recod.str(temp);
string s;
// cout<<temp<<endl;
while(recod>>s){
// cout<<s<<endl;
v.push_back(s);
}
}
}else
cerr<<" could not open:"+string(*p);
}
for (auto &str : v)
{
cout<<str<<endl;
}
結論:C ++には多くの落とし穴があります