Here's an answer with less complex while loop and no use of stringstream
s.
I've found std::stoi
/std::stof
faster than >>
operator to convert strings to numbers. Also, we have a clear indication of failure in the form of exceptions.
If you only need the sum, don't store all numbers. If the file is big, it's just memory waste.
#include<cmath>
#include<assert.h>
Unused headers.
#include <fstream>
#include <iostream>
#include <string>
int main() {
int sum = 0;
std::ifstream file_s("file1.txt");
if (file_s.bad()) {
return -1;
}
std::string word;
while (std::getline(file_s, word, ' ')) {
int number = 0;
try {
numbersum =+= std::stoi(word);
}
catch(const std::invalid_argument& ex) {
std::cout << ex.what() << ":" << word << std::endl;
}
sum += number;
}
std::cout << sum << std::endl;
return 0;
}