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 int
s or double
s. 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
Post a Comment