Read input numbers separated by spaces

前端 未结 4 1779
迷失自我
迷失自我 2021-02-01 16:49

This may be a total beginner\'s question, but I have yet to find an answer that works for me.

Currently, I\'m writing a program for a class that takes in a user\'s input

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 17:30

    int main() {
    int sum = 0;
    cout << "enter number" << endl;
    int i = 0;
    while (true) {
        cin >> i;
        sum += i;
        //cout << i << endl;
        if (cin.peek() == '\n') {
            break;
        }
        
    }
    
    cout << "result: " << sum << endl;
    return 0;
    }
    

    I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints

提交回复
热议问题