используйте c ++ для суммирования 3 целых чисел из входных данных, поэтому накопление всегда возвращает 0
Этот ответ использует push_back (), и ему не нужно знать, сколько целых чисел вводится, так каквектор будет автоматически расширяться;Таким образом, он обходит проблемы std :: vector, которые наносили ущерб вашему коду.
Учтите, что, поскольку «сколько int» может быть передано, редко фиксируется, вы, скорее всего, захотите посчитать, скольковход "на лету".Поэтому, возможно, используйте цикл, cin для локального var, затем x.push_back (a_local_var) и повторяйте до тех пор, пока какое-то условие (возможно, eof () или локальное var == -1 и т. Д.) X.size () не станет вашим счетчиком..
Вот пример работы с использованием командной строки vars и eof () (и вектора и накопления).
// Note: compile with -std=c++17 for the using comma list
#include <iostream>
using std::cout, std::cerr, std::endl, std::hex, std::dec, std::cin, std::flush; // c++17
#include <vector>
using std::vector;
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include <numeric>
using std::accumulate;
#include <cassert>
class T951_t // ctor and dtor compiler provided defaults
{
public:
int operator()(int argc, char* argv[]) { return exec(argc, argv); } // functor entry
private:
stringstream ssIn; // to simulate user input
int exec(int argc, char* argv[])
{
int retVal = initTest(argc, argv); // transfer command line strings into ssIn
if(retVal != 0) return retVal;
// ------------------------------------------------------------
// simulate unknown quantity of ints
vector<int> x;
do {
int localInt = 0;
ssIn >> localInt;
if(!ssIn.good()) // was transfer ok?
{ // no
if (ssIn.eof()) break; // but we tolerate eof
// else err and exit
cerr << "\n !ssIn.good() failure after int value "
<< x.back() << endl;
assert(0); // harsh - user typo stops test
}
x.push_back(localInt); // yes transfer is ok, put int into vector
//cout << "\n " << localInt; // diagnostic
} while(true);
showResults(x);
return 0;
}
// this test uses a stringstream (ssIn) to deliver input to the app
// ssIn is initialized from the command line arguments
int initTest(int argc, char* argv[])
{
if (argc < 2) {
cerr << "\n integer input required" << endl;
return -1;
}
// test init
for (int i=1; i < argc; ++i) {
// cout << "\n " << argv[i]; // diagnostic
ssIn << argv[i] << " "; // user text into stream
}
cout << endl;
return 0;
}
// display size and contents of vector x
void showResults(vector<int> x)
{
cout << "\n x.size(): " << x.size() << endl;
int sum = std::accumulate(x.begin(), x.end(), 0);
for (auto i : x)
cout << " " << i;
cout << endl;
cout << "\n sums to: " << sum << '\n' << endl;
}
}; // class T951_t
int main(int argc, char* argv[]) { return T951_t()(argc, argv); } // call functor
Тесты:
. / Dumy951 12 3 55 12345678900 <- ошибка после 55, потому что последнее значение int слишком большое </p>
. / Dumy951 1 2 3 y 55 12345678900 <- ошибка после значения int 3 (недопустимое значение int) </p>
. /dumy951 1 2 3 4 5 6 7 8 9 10 <- успех, результат 55 </p>