CSS Prepare

optional · CSS study notes

II.10 Standard I/O and Statements

⬆️ P-I.II. Programming Fundamentals · Question Bank · Chapter II (2016–2026)

🧠

Remember: Read → validate → compute → display.

Start here — what you should be able to do

  • Select the correct C/C++ input function and matching argument types.
  • Read names containing spaces and handle leftover newlines.
  • Explain statement categories and recover from failed input.

Reading order: foundation checks → full notes and examples → exam traps → self-test without notes → past-paper answers. All sections below remain part of the topic; code examples are kept in full.

Foundation checks

Input rules worth memorising

  • scanf("%d", &n) needs an int*; scanf("%lf", &d) needs a double*.
  • printf("%f", value) receives a double after normal argument promotion.
  • Use a width limit for C string input, or prefer fgets for a complete line.
  • gets was removed from C11; use a bounded alternative.
  • C++ numeric extraction: check if (!(cin >> n)) before using n.
  • Before a later getline, discard the remaining line when appropriate; cin.clear() clears error flags, while ignore() discards characters.
  • std::fixed << std::setprecision(2) gives two digits after the decimal point; include <iomanip>.

1. Standard I/O Streams

  • Standard input (stdin): default source of input data, normally the keyboard
  • Standard output (stdout): default destination for normal program output, normally the screen
  • Standard error (stderr): separate stream for error messages, so they can be redirected independently of normal output

2. I/O in C

  • printf() — formatted output, uses format specifiers (%d int, %f float, %c char, %s string)
  • scanf() — formatted input, requires the address-of operator & for non-string variables (e.g. scanf("%d", &age);)
  • getchar() / putchar() — unformatted single-character input/output
  • gets() / puts() — unformatted string input/output (gets() is unsafe and was removed from C11; use bounded input such as fgets)

3. I/O in C++

  • cin >> — extraction operator, reads formatted input from stdin
  • cout << — insertion operator, writes formatted output to stdout
  • cerr — writes to stderr (unbuffered, for errors)
  • getline(cin, str) — reads a full line including spaces (unlike cin >>, which stops at whitespace)

4. Formatted vs Unformatted I/O

  • Formatted I/O: data is converted to/from a specific display format using format specifiers or stream operators (printf/scanf, cin/cout)
  • Unformatted I/O: raw character-by-character transfer with no type conversion/formatting (getchar/putchar, cin.get())

5. Statement Types

Statement TypePurposeExample
DeclarationIntroduces an identifier and its typeint x;
Expression/AssignmentEvaluates an expression and optionally stores the resultx = a + b;
ControlAlters the normal sequential flowif(x\&gt;0){...}
I/OTransfers data in/out of the programcin \&gt;\&gt; x;
Compound/BlockGroups multiple statements as one unit{ stmt1; stmt2; }
NullDoes nothing (just a semicolon);

6. 💻 Code Examples: C & C++

Formatted vs unformatted I/O, and why reading a full name needs getline/care with whitespace:

C:

#include <stdio.h>
int main(void) {
    int age;
    char name[20];
    printf("Enter name and age: ");
    scanf("%19s %d", name, &age);   // & needed for age, NOT for the char array (already an address)
    printf("Hello %s, age %d\n", name, age);

    int c = getchar();                // unformatted single-character input
    putchar(c);                       // unformatted single-character output
    return 0;
}

C++:

#include <iostream>
#include <string>
using namespace std;
int main() {
    int age;
    string fullName;
    cout << "Enter age: ";
    cin >> age;
    cin.ignore();                      // discard the leftover newline before getline
    cout << "Enter full name: ";
    getline(cin, fullName);            // reads the WHOLE line, including spaces
    cout << "Hello " << fullName << ", age " << age << endl;
    cerr << "This message goes to stderr" << endl;  // separate, unbuffered stream
    return 0;
}
  • cin >> fullName alone would stop at the first space (e.g. capture only "John" from "John Smith") — getline(cin, fullName) is the fix, matching the Self-Test question above

7. MCQ Traps

  • scanf() needs &variable for primitive types (passing an address), but not for a plain char array/string, since an array name already decays to an address
  • cin >> stops reading at the first whitespace; use getline() to capture a full line with spaces
  • stderr output is typically unbuffered (shows immediately), while stdout may be buffered — relevant when a program crashes mid-execution
  • A declaration statement doesn't have to allocate an initial value; an assignment statement gives a value to an already-declared variable

8. Self-Test Questions — with answers

Q1. Differentiate stdin, stdout and stderr.

Answer

  • stdin: normal input stream.
  • stdout: normal results.
  • stderr: diagnostic messages; it can be redirected separately.
  • Example: read a number from stdin, print its square to stdout, report invalid input to stderr.

Q2. Why does scanf need &x but not &name for a character array?

Answer

  • %d requires the address of an int, so pass &x.
  • An array name usually converts to a pointer to its first element, so name already supplies a character address.
  • Use a width limit to avoid overflowing the array.

Q3. How should a full name such as John Smith be read?

Answer

  • cin >> name reads one whitespace-delimited token.
  • Use std::getline(cin, name) for a whole line.
  • If numeric extraction preceded it, handle the leftover newline first.

Q4. List six broad statement categories with examples.

Answer

  • Declaration: int x = 0;.
  • Expression/assignment: x = x + 1;.
  • Control: if (x > 0) { ... }.
  • I/O operation: cout << x;—syntactically an expression statement.
  • Compound block: { statement1; statement2; }.
  • Null statement: ;.
  • These are useful teaching categories; I/O is not a separate formal C++ statement grammar category.
  1. Differentiate stdin, stdout, and stderr.
  2. Why does scanf("%d", &x) need & but scanf("%s", name) (for a char array) does not?
  3. Why would cin >> name; fail to capture "John Smith" correctly, and what should be used instead?
  4. List the six broad categories of statements in a typical program, with one example each.

Recall check and coverage

  • Explain the three learning outcomes at the top without looking.
  • Reproduce one example or trace and test a boundary case.
  • Answer each self-test, then compare with the key.
  • Attempt each recorded past-paper task on this page.

Recorded written references: No direct written record in this topic's current notes. These concepts support the chapter's programming questions.

Evidence limit: this page preserves the question records found in your Notion notes. Disputed labels and questions not checked against original PDFs remain flagged in the Question Bank; this is not a claim of exhaustive original-paper verification.