LearnFrenzy
Sign in Take a free test

Command Line Arguments · Command Line Programs · Question 8

Repeat a word N times, with N from the command line Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Print a word repeated N times, where N and the word are given as arguments; reject a bad or negative N.

Run as: ./app 3 ha

Solution
main.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "usage: %s COUNT WORD\n", argv[0]);
        return EXIT_FAILURE;
    }
    char *end;
    long n = strtol(argv[1], &end, 10);
    if (end == argv[1] || *end != '\0' || n < 0 || n > 1000) {
        fprintf(stderr, "COUNT must be a number from 0 to 1000\n");
        return EXIT_FAILURE;
    }
    for (long i = 0; i < n; i++)
        fputs(argv[2], stdout);
    putchar('\n');
    return EXIT_SUCCESS;
}

Output Verified by compiling and running

hahaha

Validating the range as well as the format protects against both typos ("3x") and absurd values. fputs() prints the word without adding a newline.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links