Input & Output — printf, scanf, Streams

formatted I/O এবং stdin/stdout/stderr

~30 min Beginner 10 practice problems Live code

1. Standard Streams

Every C program starts with three open streams:

StreamPurposeDefault source / target
stdinStandard inputKeyboard
stdoutStandard outputTerminal (line-buffered)
stderrStandard errorTerminal (unbuffered)
প্রতিটি C প্রোগ্রাম চালু হওয়ার সাথে সাথেই তিনটি stream খোলা থাকে — stdin (keyboard থেকে পড়া), stdout (screen-এ লেখা), এবং stderr (error message-এর জন্য আলাদা channel)। Shell-এ এগুলো আলাদাভাবে redirect করা যায়, যেমন ./prog > out.txt 2> err.txt।

2. printf — Every Format Specifier

SpecExpectsExample
%dint42
%uunsigned int42
%ld %lldlong, long long9999999999
%fdouble3.14
%e / %gscientific / shortest1.23e+05
%cint (character)A
%snull-terminated stringHello
%x / %Xint as hex2a / 2A
%oint as octal52
%ppointer0x7ffc...
%zusize_t8
%%literal %%
Width & Precision — Live Demo
width_precision.c
#include <stdio.h>

int main(void) {
    printf("[%5d]\n", 42);        // width 5, right-aligned
    printf("[%-5d]\n", 42);       // left-aligned
    printf("[%05d]\n", 42);       // zero-padded
    printf("[%.3f]\n", 3.14159);  // 3 decimal places
    printf("[%10.3f]\n", 3.14159); // width 10, 3 decimals
    printf("[%10s]\n", "Dhaka");   // right-aligned string
    printf("[%-10s]\n", "Dhaka");  // left-aligned string
    return 0;
}

3. scanf — Reading Input (Handle With Care)

int age;
scanf("%d", &age);        // note the &
printf("You are %d\n", age);
  • Pass the address of the variable — always with &.
  • scanf skips leading whitespace for %d, %f, %s — but not for %c.
  • Check its return value — it reports how many items were successfully read.
scanf("%s", buf) is a buffer-overflow waiting to happen সবসময় size limit দিন: scanf("%99s", buf) যদি buffer-এর আকার 100 হয়। আরও ভালো সমাধান হলো fgets।
Safer Input — fgets
safe_input.c — stdin: Nusrat Jahan
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[100];
    if (fgets(name, sizeof name, stdin)) {
        // strip trailing newline if present
        size_t n = strlen(name);
        if (n && name[n-1] == '\n') name[n-1] = '\0';
        printf("Hello, %s! Your name has %zu characters.\n", name, strlen(name));
    }
    return 0;
}

4. Character I/O — getchar / putchar

uppercase.c — stdin: hello
#include <stdio.h>
#include <ctype.h>

int main(void) {
    int c;
    while ((c = getchar()) != EOF) putchar(toupper(c));
    return 0;
}
getchar char নয় বরং int return করে — কারণ তাকে EOF (−1)-ও ফেরত দিতে হতে পারে।

5. stderr — For Error Messages

fprintf(stderr, "Error: could not open file %s\n", name);

কেন আলাদা? কারণ shell-এ এগুলো স্বাধীনভাবে redirect করা যায় — সাধারণ output আর error আলাদা জায়গায় পাঠানো যায়।

6. Buffer Flushing

Terminal-এ stdout সাধারণত line-buffered — অর্থাৎ \n না আসা পর্যন্ত বা buffer পূর্ণ না হওয়া পর্যন্ত output দেখা যায় না। Pipe বা ফাইলে redirect করলে এটি fully buffered হয়।

printf("Processing...");   // may not appear yet
fflush(stdout);             // force flush

7. A Complete Interactive Program

profile.c — stdin: Arif / 25 / 3.85
#include <stdio.h>

int main(void) {
    char   name[50];
    int    age;
    double gpa;

    if (scanf("%49s", name) != 1) return 1;
    if (scanf("%d", &age)    != 1) return 1;
    if (scanf("%lf", &gpa)   != 1) return 1;

    printf("\n--- Profile ---\n");
    printf("Name : %-20s\n", name);
    printf("Age  : %5d\n", age);
    printf("GPA  : %6.2f\n", gpa);
    return 0;
}

8. Practice Problems

  1. Read three integers from stdin and print their sum and average (2 decimal places).
    Stdin থেকে তিনটি পূর্ণসংখ্যা নিন এবং তাদের যোগফল ও গড় (২ দশমিক) প্রিন্ট করুন।
    ✨ Show Answer
    three.c — stdin: 10 20 30
    #include <stdio.h>
    int main(void) {
        int a, b, c;
        scanf("%d %d %d", &a, &b, &c);
        int sum = a + b + c;
        printf("Sum = %d\n", sum);
        printf("Avg = %.2f\n", sum / 3.0);
        return 0;
    }
  2. Read a float and print it rounded to 0, 2 and 4 decimal places.
    একটি float নিয়ে 0, 2 ও 4 দশমিক স্থানে প্রিন্ট করুন।
    ✨ Show Answer
    round.c — stdin: 3.14159265
    #include <stdio.h>
    int main(void) {
        double x;
        scanf("%lf", &x);
        printf("%.0f\n%.2f\n%.4f\n", x, x, x);
        return 0;
    }
  3. Print a table of squares from 1 to 10 aligned in columns.
    ১ থেকে ১০ পর্যন্ত বর্গের একটি সারণি সারিবদ্ধভাবে প্রিন্ট করুন।
    ✨ Show Answer
    squares.c
    #include <stdio.h>
    int main(void) {
        printf("%4s %6s\n", "n", "n*n");
        for (int i = 1; i <= 10; i++)
            printf("%4d %6d\n", i, i*i);
        return 0;
    }
  4. Read a character and print its char and ASCII value.
    একটি character নিয়ে তার character ও ASCII মান প্রিন্ট করুন।
    ✨ Show Answer
    char_ascii.c — stdin: A
    #include <stdio.h>
    int main(void) {
        char c;
        scanf(" %c", &c);
        printf("char='%c', ASCII=%d\n", c, c);
        return 0;
    }
  5. Read a line of text with fgets and print it back with its length.
    fgets দিয়ে একটি লাইন পড়ুন এবং সেটি ও তার length প্রিন্ট করুন।
    ✨ Show Answer

    উপরের Section 3-এর safe_input.c-ই সম্পূর্ণ উত্তর — সেটাই copy করুন।

  6. Read N, then read N numbers and print the maximum. Check scanf's return value.
    প্রথমে N, তারপর N সংখ্যা নিয়ে maximum প্রিন্ট করুন। scanf-এর return value যাচাই করুন।
    ✨ Show Answer
    max_n.c — stdin: 5 / 12 7 99 3 42
    #include <stdio.h>
    #include <limits.h>
    int main(void) {
        int n;
        if (scanf("%d", &n) != 1) return 1;
        int mx = INT_MIN, x;
        for (int i = 0; i < n; i++) {
            if (scanf("%d", &x) != 1) return 1;
            if (x > mx) mx = x;
        }
        printf("Max = %d\n", mx);
        return 0;
    }
  7. Write a program whose errors go to stderr instead of stdout.
    Error message stdout না, stderr-এ পাঠান।
    ✨ Show Answer
    stderr.c
    #include <stdio.h>
    int main(void) {
        printf("This goes to stdout.\n");
        fprintf(stderr, "This goes to stderr.\n");
        return 0;
    }

    Shell-এ দুটি আলাদাভাবে redirect করা যায়: ./prog > out.txt 2> err.txt।

  8. Print a number in decimal, uppercase hex and octal — on one line.
    একটি সংখ্যা decimal, uppercase hex এবং octal-এ এক লাইনে প্রিন্ট করুন।
    ✨ Show Answer
    bases.c — stdin: 255
    #include <stdio.h>
    int main(void) {
        int n;
        scanf("%d", &n);
        printf("dec=%d  hex=%X  oct=%o\n", n, n, n);
        return 0;
    }
  9. Read hours, minutes and seconds and print them as HH:MM:SS with zero-padding.
    ঘণ্টা, মিনিট ও সেকেন্ড নিয়ে শূন্য দিয়ে pad করে HH:MM:SS format-এ প্রিন্ট করুন।
    ✨ Show Answer
    time.c — stdin: 9 5 3
    #include <stdio.h>
    int main(void) {
        int h, m, s;
        scanf("%d %d %d", &h, &m, &s);
        printf("%02d:%02d:%02d\n", h, m, s);
        return 0;
    }
  10. What does scanf(" %c", &c) do differently from scanf("%c", &c)?
    scanf(" %c", &c) আর scanf("%c", &c)-এর পার্থক্য কী?
    ✨ Show Answer

    %c default-ভাবে whitespace (space, tab, newline) skip করে না। তাই আগের scanf থেকে buffer-এ থেকে যাওয়া \n ধরে ফেলে। " %c" লিখলে leading whitespace skip হয় — এটি নতুন character পড়ে।

Glossary (শব্দকোষ)

TermMeaningবাংলায়
I/OInput/Output — communication between a program and the world.প্রোগ্রাম ও বাইরের জগতের মধ্যে যোগাযোগ।
StreamA sequence of bytes flowing in or out of a program.প্রোগ্রামে আসা-যাওয়া byte-এর ধারা।
stdinStandard input stream (usually keyboard).স্ট্যান্ডার্ড input (সাধারণত কীবোর্ড)।
stdoutStandard output stream (usually terminal).স্ট্যান্ডার্ড output (সাধারণত টার্মিনাল)।
stderrStandard error stream — for error messages.Error message-এর জন্য আলাদা stream।
printfFormatted output to stdout.Stdout-এ ফরম্যাট-যুক্ত output লেখার ফাংশন।
scanfFormatted input from stdin.Stdin থেকে ফরম্যাট-যুক্ত input পড়ার ফাংশন।
Format SpecifierA code (%d, %s, %f) describing data type.Data type বর্ণনাকারী কোড।
fgetsReads a line of text safely with size limit.Size সীমাসহ নিরাপদভাবে এক লাইন পড়ার ফাংশন।
getchar / putcharRead/write a single character.একটি character read/write করার ফাংশন।
fflushForces a buffered stream to write its contents.Buffer-এ থাকা data জোর করে লিখিয়ে দেয়।
Buffered I/OI/O that batches data for efficiency.দক্ষতার জন্য I/O-কে দলবদ্ধ করা।
EOFEnd-of-file marker — no more input."ফাইল শেষ" নির্দেশক।

Summary — Module 08

printf ও scanf — C I/O-র দুই স্তম্ভ। প্রতিটি format specifier সঠিক type-এর সাথে মিলিয়ে লিখুন। scanf-এ & দেওয়া ভুলবেন না। scanf("%s")-এর বদলে fgets ব্যবহার করুন। error message stderr-এ পাঠান এবং return value যাচাই করুন।

Next Module → Control Flow I — if, else, switch।