哪位帮我写一个C++小程序。
提示用户输入任意多个整数(每个数用空格号隔开),按回车后便便显示各个数相加的和。例:
输入:1 2 3 4 按回车后
结果:10
参考答案:没看清楚题,是要打出总和而不是输入的值,特做此修改:
#include <iostream>
#include <vector>
int main( ){
using namespace std;
cout << "请输入任意多个整数(用空格隔开):";
vector<int> arr;
int num;
while(cin >> num && cin.get() != '\n'){
arr.push_back(num);
}
arr.push_back(num);
int sum(0);
cout << "\n元素: {";
for(vector<int>::iterator ite = arr.begin( );ite != arr.end( ); ++ite){
cout << " "<< *ite << " ";
sum += *ite;
}
cout << "}\n\n"<< "总和为: " << sum << endl;
}
回银河飞将26:STL和Standard C++ library是2回事,STL的部分容器确实已经成为了C++标准的一部分,那是1994年的事。我用的完全是C++的标准。以下是我的读书摘选:
Distinguish between stdlib & STL
There is often a bit of confusion between the containers and algorithms in the Standard C++ Library, and the entity known as the STL. The Standard Template Library was the name Alex Stepanov (who was working at Hewlett-Packard at the time) used when he presented his library to the C++ Standards Committee at the meeting in San Diego, California in Spring 1994. The name stuck, especially after HP decided to make it available for public downloads. Meanwhile, the committee integrated it into the Standard C++ Library, making a large number of changes. STL's development continues at Silicon Graphics (SGI; see ). The SGI STL diverges from the Standard C++ Library on many subtle points. So although it's a popular misconception, the C++ Standard does not “include” the STL. It can be a bit confusing since the containers and algorithms in the Standard C++ Library have the same root (and usually the same names) as the SGI STL. In this book, I will say “The Standard C++ Library” or “The Standard Library containers,” or something similar and will avoid the term “STL.”
Picked from Thinking in C++ 2nd edition Vol1->
->chapter 2->more about iostreams->introducing vector