一道极其简单的ACM题,为什么第2段代码通不过测试?
http://acm.hziee.edu.cn/showproblem.php?pid=1096
题目
Your task is to calculate the sum of some integers.
Input
Input contains an integer N in the first line, and then N lines follow. Each line starts with a integer M, and then M integers follow in the same line.
Output
For each group of input integers you should output their sum in one line, and you must note that there is a blank line between outputs.
Sample Input
3
4 1 2 3 4
5 1 2 3 4 5
3 1 2 3
Sample Output
10
15
6
第一段代码,通过测试
# include <iostream>
using namespace std;
int main()
{
int m,n,s;
int sum;
cin>>n;
for(int i=0;i<n;i++)
{
if(i)
cout<<endl;
cin>>m;
sum=0;
for(int j=0;j<m;j++)
{
cin>>s;
sum+=s;
}
cout<<sum<<endl;
}
return 0;
}
第2段代码,通不过测试,why?
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <sstream>
using namespace std;
int main(void)
{
int times;
cin>>times;
while(times--!=-1){
string str;
istringstream istr;
int temp;
getline(cin,str);
istr.str(str);
vector<int> array;
bool ignore=true;
while(!istr.eof()){
istr>>temp;
if(ignore==true) {ignore=false;continue;}
array.push_back(temp);
}
if(!array.empty()) cout<<accumulate(array.begin(), array.end(),0)<<"\n"<<endl;
}
return 0;
}
有时候第2段代码会得出奇怪的结果,这是为什么?