Produce the sum of all white space separated integers in a given file
You collect all numbers but then use the collection only for the sum. Better just update the sum. And I find the whole trying int and if fails use word a bit complicated. How about just always reading words and then reading numbers from them? (The &gt;&gt; writes zero if there's no number.)
#include &lt;fstream&gt;
#include &lt;iostream&gt;
#include &lt;sstream&gt;
#include &lt;string&gt;
using namespace std;

int main() {
    int sum = 0;
    ifstream file(&quot;file1.txt&quot;);
    string word;
    while (file &gt;&gt; word) {
        int number;
        istringstream(word) &gt;&gt; number;
        sum += number;
    }
    cout &lt;&lt; sum &lt;&lt; endl;
}