Accessing Vectors In C++ -


i wrote simple program accesses file called "input.txt" , pushes contents vector of string type.

#include <iostream> #include <vector> #include <fstream>  using namespace std;  int main() {     fstream input;     input.open("input.txt");     string s;     input >> s;     while (!input.eof())     {         cout << s <<endl;         input >> s;         vector<string> v;         v.push_back(s);     }     input.close();  } 

i know isn't best way there way can access vector , use equation? if wanted add elements of vector , find sum?

for starters, here's cleaner version of code you've written:

ifstream input("input.txt"); string s; while (input >> s) {     cout << s << endl;     vector<string> elems;     elems.push_back(s); } 

this uses ifstream instead of fstream, seems appropriate here since aren't using write facilities of fstream. combines read logic loop condition, simplifying logic when continue.

one thing seems weird code you've scoped vector lives 1 loop iteration. consequently, every iteration, lose old vector contents. moving out of loop fix this:

ifstream input("input.txt"); vector<string> elems;  string s; while (input >> s) {     cout << s << endl;     elems.push_back(s); } 

finally, if want loop on elements of vector adding them together, don't want reading file strings, rather ints or doubles. saves hassle of having convert values later. example:

ifstream input("input.txt"); vector<double> elems;  double s; while (input >> s) {     cout << s << endl;     elems.push_back(s); } 

now, can add values this:

double total = 0.0; (int = 0; < elems.size(); ++i)     total += elems[i]; 

or, better, can add using accumulate algorithm <numeric>:

double total = accumulate(elems.begin(), elems.end(), 0.0); 

hope helps!


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -