CSE 40872 Lecture 002

Topic:I/O parsing and manipulation
Author: Peter Bui <pbui@cse.nd.edu>
Date: August 28, 2009

I/O in Programming Contests

No need to open physical files

Example Input

Problem 001:

1 13
4 8
0 1000

I/O tends to be line-oriented plain text

C Input

char   c;
int    i;
float  f;
double d;
char   s[BUFFER_SIZE];

scanf("%c %d %f %lf %s", &c, &i, &f, &d, &s);

C Input (Continued)

char s[BUFFER_SIZE];
int  i;

if (fgets(s, BUFFER_SIZE, stdin) != NULL) {
    sscanf(s, "%d", &i);
}

Example Read (C)

Problem 001:

int start, end;

while (scanf("%d %d", &start, &end) == 2) {
    // generate range and check if palindrome
}

C Output

printf("%c %d %f %lf %s\n", c, i, f, d, s);
snprintf(s, BUFFER_SIZE, "%d", i); // itoa
printf("%0.2lf\n", d);

C++ Input

using namespace std;
int start, end;

cin  >> start >> end;

C++ Input (Continued)

stringstream ss;

ss << i << ' ' << s << endl;

C++ Input (Continued)

string s;

while (!getline(cin, s).eof()) {
    // process line
}

Example Read (C++)

Problem 001:

int start, end;

while (true) {
    cin >> start >> end;
    if (cin.eof()) break;
}

C++ Output

cout << str << ' ' << i << endl;
cout.width(8)
cout << right << fixed << d << endl;