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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!