开发者

stringstream problem - vector iterator not dereferencable

I've got a problem with the following code snippet.

It is related to the stringstream "stringstream css(cv.back())" bit. If it is commented out the program will run ok.

It is really weird, as I keep getting it in some of my programs, but if I just create a console project the code will run fine. In some of my Win32 programs it will and in some it won't (then it will return "vector iterator not dereferencable" but it will compile just fine).

Any ideas at all would be really appreciated. Thanks!

vector<double> cRes(2);
vector<double> pRes(2);

int readTimeVects2(vector<double> &cRes, vector<double> &pRes){
 开发者_运维技巧   string segments;
    vector<string> cv, pv, chv, phv;
    ifstream cin("cm.txt");
    ifstream pin("pw.txt");
    ifstream chin("hm.txt");
    ifstream phin("hw.txt");

    while (getline(cin,segments,'\t')) {
        cv.push_back(segments);
    }

    while (getline(pin,segments,'\t')) {
        pv.push_back(segments);
    }

    while (getline(chin,segments,'\t')) {
        chv.push_back(segments);
    }

    while (getline(phin,segments,'\t')) {
        phv.push_back(segments);
    }

    cin.close();  
    pin.close();  
    chin.close();   
    phin.close();

    stringstream phss(phv.front());
    phss >> pRes[0];
    phss.clear();
    stringstream chss(chv.front());
    chss >> cRes[0];
    chss.clear();

    stringstream pss(pv.back());
    pss >> pRes[1];
    pss.clear();
    stringstream css(cv.back());
    css >> cRes[1];
    css.clear();

    return 0;
}


There are two major issues here. Either or both of these problems can be causing the issue you are experiencing.

You are hiding names from outside your scope:

vector<double> cRes(2);
vector<double> pRes(2);

int readTimeVects2(vector<double> &cRes, vector<double> &pRes){

cRes and pRes are going to be the variables passed to your function, not the global variables you have demonstrated.

You need to show us the calling code where the issue occurs before we will be able to diagnose this problem -- though I wonder why you're not just using push_back here,


There's another problem here:

stringstream phss(phv.front());
stringstream chss(chv.front());
stringstream pss(pv.back());
stringstream css(cv.back());

You have no checking to ensure phv, chv, pv, and cv are not empty. It's entirely possible your std::getlines above had problems that prevented them from completing successfully, and it's also entirely possible that the files you passed were empty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜