DPST1091 Revision Command Line Arguments Sample Solutions
Revision Exercise: Convert digits to these characters
The mapping for digits will be given to your program as a single command line argument.
This command line argument will contain 10 characters. These are the characters the corresponding digit should be replaced with. For example, '0's should be replaced with the first character of the command line argument, '1' with the second character of the command line argument and so on.
Characters other than digits should not be changed.
Your program should stop only at the end of input.
For example:
dcc -o map_digits map_digits,c ./map_digits ABCDEFGHIJ 0123456789 ABCDEFGHIJ Andrew rocks! Andrew rocks! 6 * 7 = 42 G * H = EC This is week 9 of COMP1511 This is week J of COMPBFBB ./map_digits andrewrock two 4 eight 16 thirtytwo 64 two e eight nr thirtytwo re ./map_digits zyzuvtsrqp 1 2 4 8 16 32 64 128 256 y z v q ys uz sv yzq zts
You can assume that your program is given exactly one command line argument and it contains exactly 10 characters.
No error checking is necessary.
When you think your program is working you can use autotest
to run some simple automated tests:
1091 autotest map_digits
map_digits.c
// Written 3/5/2018 by Andrew Taylor (andrewt@unsw.edu.au)
// Write stdin to stdout with digits mapped to specified characters
//
// The mapping will be supplied as a command-line argument containing 10 characters:
#include <stdio.h>
#include <string.h>
#define N_DIGITS 10
int map_digit(int character, char digit_mapping[N_DIGITS]);
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <mapping>\n", argv[0]);
return 1;
}
if (strlen(argv[1]) != N_DIGITS) {
fprintf(stderr, "%s: mapping must contain %d letters\n", argv[0], N_DIGITS);
return 1;
}
int character = getchar();
while (character != EOF) {
int new_character = map_digit(character, argv[1]);
putchar(new_character);
character = getchar();
}
return 0;
}
// encrypt letters with a map_digits cipher with the specified mapping
int map_digit(int character, char digit_mapping[N_DIGITS]) {
if (character >= '0' && character <= '9') {
return digit_mapping[character - '0'];
} else {
return character;
}
}