有关c++ istringstream的一个坑

c++primer练习8.11
:本节的程序在外层while循环中定义了istringstream对象。如果record对象定义在循环之外,你需要对程序进行怎样的修改?重新程序,将record的定义移到while循环之外,验证你设想的修改方法是否正确?
(大概意思是读取argv[]得到文件,用getline从中读取每一行,再用istringstream提取出每个单词)

(下为我开始的程序)

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提到外面,但是答案怎么就错了???
本应读取所有行,但却只读取了一行的几个单词!!!

	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;
    }
    

错误原因:一个 istringstream流在读到结尾是会把eofbit,failbit置位,此时我们再使用 istringstream流读入是失败的。
解决方案:调用istringstream流的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++坑多

猜你喜欢

转载自blog.csdn.net/adlatereturn/article/details/105055646