2015/05/18

【C++】讀取整行數字




1. include
?
1
2
#include <sstream>
#include <iostream>

2. 簡單範例,輸入並相加
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <sstream>
#include <iostream>
using namespace std;
int main(){
    string line;
    int sum, tmp, flag=1;
    while (flag && getline(cin, line)) {
        sum = 0;
        istringstream in(line);
        while (in>>tmp) {
            if (tmp==0) flag = 0;
            sum += tmp;
        }
        if (flag) printf("sum  = %d\n", sum);
    }
    return 0;
}

3. 範例輸入輸出:
1 2 3 4
sum  = 10
1 2 3 4 5
sum  = 15

0