TermIO.c
#include <stdio.h> int main() { int i; int sum = 0; char ch; printf("Enter a sequence of integers: "); while ( scanf_s( "%d", &i ) == 1 ) { /* (A) */ sum += i; /* (B) */ while ( ( ch = (char) getchar() ) == ' ' ) /* (C) */ ; if ( ch == '\n' ) break; ungetc( ch, stdin ); /* (D) */ } printf( "The sum of the integers is: %d\n", sum ); return 0; }
TermIO.cpp
#include <iostream> using namespace std; int main() { int sum = 0; cout << "Enter a sequence of integers: "; int i; while ( cin >> i ) { //(A) sum += i; while ( cin.peek() == ' ' ) cin.get(); //(B) if ( cin.peek() == '\n' ) break; //(C) } cout << "Sum of the numbers is: " << sum << endl; return 0; }
TermIO.java
import java.io.*; class TermIO { static boolean newline; //(A) public static void main( String[] args ) { int sum = 0; System.out.println( "Enter a sequence of integers: " ); while ( newline == false ) { String str = readString(); //(B) if ( str != null ) { int i = Integer.parseInt( str ); //(C) sum += i; } } System.out.println( "Sum of the numbers is: " + sum ); } static String readString() { //(D) String word = ""; try { int ch; while ( ( ch = System.in.read() ) == ' ' ) //(E) ; if ( ch == '\n' ) { //(F) newline = true; //(G) return null; //(H) } word += (char) ch; //(I) while ( ( ch = System.in.read() ) != ' ' && ch != '\n' && ch != '\r' ) //(J) word += (char) ch; //(K) if ( ch == '\r' || ch == '\n' ) newline = true; //(L) } catch( IOException e ) {} return word; //(M) } }
TermIO.py
' example demonstrating input from console terminal ' str = raw_input('Enter a sequence of integers: ') a = str.split() b = [] for v in a: b.append(int(v)) print 'The sum of the integers is %d' % sum(b)
Maintained by John Loomis, last updated 29 Dec 2006