Read some tricky input format in C/C++

Problem 1

Format
Input:
+ 2 integer numbers on each line
+ end of input when 2 numbers are both equal to 0
Output:
+ sum of 2 numbers on each line

Code C

int a, b;
while( scanf("%d %d", &a, &b), (a || b) ) {
    printf("%d\n", a + b);
}

 

Code C++

int a, b;
while( cin >> a >> b, (a || b) ) {
    cout << a + b << '\n';
}

Problem 2

Format
Input:
+ 2 integer numbers on each line
Output:
+ sum of 2 numbers on each line

E.x 
Input:
1 2
3 4
Output:
3
7

Code C

int a, b;
while( scanf("%d %d", &a, &b) == 2 ) {
// while ( scanf("%d %d", &a, &b) != EOF ) {
    printf("%d\n", a + b);
}

Code C++

int a, b;
while( cin >> a >> b ) {
    cout << a + b << '\n';
}

Problem 3

Format
Input:
+ some integers on each line
Output:
+ sum of 2 numbers on each line

E.x 
Input:
1 2 3
4 5
6 7 8 9
Output:
6
9
30

Code C++

string s;
while( getline(cin, s) ) {
    istringstream iss(s);
    int sum = 0;
    int v;
    while( iss > v ) sum += v;
    cout << sum << '\n';
}

Happy coding

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s