简体   繁体   中英

How do I input values from a file into a vector?

I've been having trouble with this bit of code for a while now.

void readData(const string & filename, vector<double> & fpAngle, vector<double> & liftCo) {

ifstream inFS(filename);
double num1;
double num2;

inFS.open(filename);

if (!inFS.is_open()) {
    cout << "Error opening " << filename << endl;
    exit (1);
}

while (inFS >> num1 >> num2) {
    if (!inFS.fail()) {
        fpAngle.push_back (num1);
        liftCo.push_back (num2);
    }
}

inFS.close();

return; 

For this situation I am extracting values from a file that are formatted into 2 columns and I have to store both columns into their respective vectors. No matter what I try, I can never get the correct amount of values into both vectors. Is there something I'm missing here? Thanks.

Edit: The problem has been solved. I took moldbdnilo's suggestion and edited the code accordingly, removing open/close as well as (!infs.fail()) which got the code to work. Thank you, and apologies for possibly not being more thorough about my question.

This should work for you with couple of changes.

int main()
{

    ifstream inFile;
    inFile.open(filename);
    if (inFile.fail()) {
         cout << "Error opening " << filename << endl;
    }
   std::vector<std::string> code;
    string S;
   while(fh>>s){
             code.push_back(s);
    }

    for(int i=0; i<vs.size(); i++){

            std::cout<<code[i]<<std::endl;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM