链接:https://ac.nowcoder.com/acm/contest/5657/G
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld
题目描述
计算一系列数的和
打开以下链接可以查看正确的代码
https://ac.nowcoder.com/acm/contest/5657#question

输入描述:
输入数据有多组, 每行表示一组输入数据。

每行不定有n个整数,空格隔开。(1 <= n <= 100)。
输出描述:
每组数据输出求和的结果
示例1
输入
复制
1 2 3
4 5
0 0 0 0 0
输出
复制
6
9
0

1.c++

(1)getline(cin, string)

借助stringstream
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string line;
    while (getline(cin, line))
    {
        stringstream ss;
        ss << line;
        int cur_sum = 0;
        int x;
        while (ss >> x)
            cur_sum += x;
        cout << cur_sum << endl;
    }
    return 0;
}

稍微优化一下

#include <iostream>
#include <cstring>
#include <algorithm>
#include <sstream>

using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    string line;
    while (getline(cin, line))
    {
        stringstream ss;
        ss << line;
        int cur_sum = 0;
        int x;
        while (ss >> x)
            cur_sum += x;
        cout << cur_sum << endl;
    }
    return 0;
}

(2)每次cin>>,判断下一位是不是换行符 cin.get() == '\n'

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int cur_sum = 0;
    int x;
    while (cin >> x)
    {
        cur_sum += x;
        if (cin.get() == '\n')
        {
            cout << cur_sum << endl;
            cur_sum = 0;
        }
    }

    return 0;
}

稍微优化一下

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int cur_sum = 0;
    int x;
    while (cin >> x)
    {
        cur_sum += x;
        if (cin.get() == '\n')
        {
            cout << cur_sum << endl;
            cur_sum = 0;
        }
    }

    return 0;
}

2.python3 [int(x) for x in input().split()]

while True:
    try:
        nums = [int(x) for x in input().split()]
        print(sum(nums))
    except:
        break

3.java scan.hasNextLine() scan.nextLine().split(" ")

import java.util.* ;

public class Main
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);

        while (scan.hasNextLine())
        {
            String [] nums = scan.nextLine().split(" ");

            int cur_sum = 0;
            for (String x : nums)
                cur_sum += Integer.parseInt(x);

            System.out.println(cur_sum);
        }

    }
}