Character I/O¶
The Outside World¶
stdio.h
: functions and constants for I/O
Standard input and output
File I/O
Formatted
Buffered
Most simple ones first:
int c;
c = getchar();
putchar(c);
cat
for the Poor (1)¶
#include <stdio.h>
int main(void)
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
return 0;
}
cat
for the Poor (2)¶
while (c != EOF)
|
|
But ugly code duplication: getchar()
called twice
while ((c = getchar()) != EOF)
putchar(c);
|
|
More Examples …¶
long nc = 0;
while (getchar() != EOF)
++nc;
|
Counting input characters
|
long nc;
for (nc = 0; getchar() != EOF; ++nc);
|
Same with Just more obscure |
More Examples - if
¶
Counting lines: \n
terminates a line
int c, nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
if
: alright==
: equality; but inappropriate for floating point numbers\n
: character constant for newline (linefeed), ASCII 10 (0A)
if
, Formally¶
if (expression)
true-statement
else // optional
false-statement
Statement can be:
Single statement (terminated with ‘;’)
Multiple statements, grouped inside
{ ... }
Operators, Formally¶
|
Equality |
|
Inequality |
|
Boolean AND |
|
Boolean OR |
|
Boolean NOT |