JV
C

Java to C

10 lessons

Progress0%
1Introduction to C2Data Types3Pointers4Strings5Memory Management6Structs vs Classes7Preprocessor and Header Files8Multi-File Programs9Input / Output and Command-Line Args10Arrays: Sorting and Searching
All Mirror Courses
JV
C
Input / Output and Command-Line Args
MirrorLesson 9 of 10
Lesson 9

Input / Output and Command-Line Args

C uses scanf/printf and argc/argv for I/O and arguments; Java uses Scanner/System.out and String[] args.

Introduction

In this lesson, you'll learn about input / output and command-line args in C. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.

Mirror Card
JV
From Java:

In Java, you're familiar with c uses scanf/printf and argc/argv for i/o and arguments; java uses scanner/system.out and string[] args..

C
In C:

C has its own approach to c uses scanf/printf and argc/argv for i/o and arguments; java uses scanner/system.out and string[] args., which we'll explore step by step.

The C Way

Let's see how C handles this concept. Here's a typical example:

C
C Example
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    /* Command-line arguments */
    if (argc > 1) {
        printf("First arg: %s\n", argv[1]);
    }
    /* argc = argument count (includes program name)
       argv[0] = program name
       argv[1..argc-1] = user-provided args */

    /* Interactive input */
    char name[64];
    int age;

    printf("Enter name: ");
    fgets(name, sizeof(name), stdin);
    /* fgets keeps the newline — strip it */
    name[strcspn(name, "\n")] = '\0';

    printf("Enter age: ");
    if (scanf("%d", &age) != 1) {
        fprintf(stderr, "Invalid age\n");
        return 1;
    }

    printf("Hello %s, you are %d years old\n", name, age);
    return 0;
}

Comparing to Java

Here's how you might have written similar code in Java:

JV
Java (What you know)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Command-line arguments
        if (args.length > 0) {
            System.out.println("First arg: " + args[0]);
        }

        // Interactive input
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter name: ");
        String name = sc.nextLine();

        System.out.print("Enter age: ");
        int age = sc.nextInt();

        System.out.printf("Hello %s, you are %d years old%n", name, age);
        sc.close();
    }
}
Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

C
In C:

argc/argv vs String[] args — argc includes the program name at argv[0]; Java args[0] is the first user argument

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

C
In C:

scanf reads formatted input (like Java Scanner.nextInt), but returns the count of items matched — always check

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

C
In C:

Use fgets for strings instead of scanf("%s") — fgets respects the buffer size; scanf("%s") overflows

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

C
In C:

printf format specifiers: %s string, %d int, %f float, %ld long, %zu size_t — no automatic type deduction

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

C
In C:

stderr (standard error) vs stdout — use fprintf(stderr, ...) for error messages; they go to a separate stream

Step-by-Step Breakdown

1. argc and argv

main receives argument count and argument vector. argv[0] is the program name; user args start at argv[1]. Always bounds-check argc before reading argv.

JV
Java
public static void main(String[] args) {
    if (args.length > 0) System.out.println(args[0]);
}
C
C
int main(int argc, char *argv[]) {
    if (argc > 1) printf("%s\n", argv[1]);
    return 0;
}
/* argc includes program name: argc >= 1 always */

2. printf Formatting

printf uses format specifiers: %s (string), %d (int), %f (float), %ld (long), %zu (size_t). Use \n for newline; Java's %n is platform-line-ending-aware but C doesn't have it.

JV
Java
System.out.printf("%-10s %5d %8.2f%n", name, age, salary);
C
C
printf("%-10s %5d %8.2f\n", name, age, salary);
/* %-10s: left-aligned string, 10 wide
   %5d:   right-aligned int, 5 wide
   %8.2f: float, 8 wide, 2 decimal places */

3. Reading Strings Safely

Never use scanf("%s") — it reads until whitespace and has no length limit. Use fgets instead: it reads a whole line and respects the buffer size.

JV
Java
String name = scanner.nextLine();
C
C
char name[64];
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0';  /* strip newline */
Common Pitfall
scanf("%s", buf) is a buffer overflow — use fgets(buf, sizeof(buf), stdin) for all string input.

4. Reading Numbers

scanf returns the count of successfully matched items — always check it to detect invalid input.

JV
Java
int n = scanner.nextInt();
C
C
int n;
if (scanf("%d", &n) != 1) {
    fprintf(stderr, "Expected integer\n");
    return 1;
}
/* &n — pass address so scanf can write the value */
Rule of Thumb
Always pass the address (&var) to scanf for non-pointer types. Check the return value — it tells you how many items were successfully parsed.

Common Mistakes

When coming from Java, developers often make these mistakes:

  • argc/argv vs String[] args — argc includes the program name at argv[0]; Java args[0] is the first user argument
  • scanf reads formatted input (like Java Scanner.nextInt), but returns the count of items matched — always check
  • Use fgets for strings instead of scanf("%s") — fgets respects the buffer size; scanf("%s") overflows
Common Pitfall
Don't assume C works exactly like Java. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • argc/argv: argc includes program name (argv[0]); user args start at argv[1]
  • printf format: %s string, %d int, %f float, %ld long — no automatic type detection
  • fgets(buf, size, stdin) is safe for string input; scanf("%s") is a buffer overflow vulnerability
  • scanf returns the matched item count — check it to validate numeric input
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your Java code in C to practice these concepts.
PreviousNext