For starters, here's a much cleaner version of the code you've just 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
, which seems appropriate here since you aren't using the write facilities of fstream
. It also combines the read logic with the loop condition, simplifying the logic for when to continue.
One thing that seems weird with this code is that you've scoped the vector
so that it only lives for one loop iteration. Consequently, every iteration, you lose all your old vector
contents. Moving this out of the loop would probably fix this:
ifstream input("input.txt");
vector<string> elems;
string s;
while (input >> s) {
cout << s << endl;
elems.push_back(s);
}
Finally, if you want to loop over the elements of the vector
adding them together, you probably don't want to be reading the file as strings, but rather as int
s or double
s. This saves you the hassle of having to convert the values later. For example:
ifstream input("input.txt");
vector<double> elems;
double s;
while (input >> s) {
cout << s << endl;
elems.push_back(s);
}
Now, you can add all the values together like this:
double total = 0.0;
for (int i = 0; i < elems.size(); ++i)
total += elems[i];
Or, even better, you can add everything together using the accumulate
algorithm from <numeric>
:
double total = accumulate(elems.begin(), elems.end(), 0.0);
Hope this helps!