patterncMinor
Happy Birthday Program
Viewed 0 times
birthdayprogramhappy
Problem
I'm trying to teach myself C. I've managed to make this program I call HappyToYou.c (inspired by this video):
I think it is free from bugs (as far as I know). I'm pretty sure it can be trimmed down but I'm not sure how.
#include
//#include //malloc would need this.
#include
#include
void sing(char *start, char *end){
printf("%s%s.\n", start, end);
}
int main(int argc, char *argv[]){
if(argc!=3) errx(1, "Give a holiday and a name as arguments.");
char *happy="Happy ";
char start[strlen(happy)+strlen(argv[1])+1];
strcpy(start, happy);
strcat(start, argv[1]);
char *to=" to you";
char *dear=" dear, ";
char person[strlen(dear)+strlen(argv[2])+1];
strcpy(person, dear);
strcat(person, argv[2]);
sing(start, to);
sing(start, to);
sing(start, person);
sing(start, to);
return 0;
}I think it is free from bugs (as far as I know). I'm pretty sure it can be trimmed down but I'm not sure how.
Solution
There're some bugs in the code. For example, if the user provides more inputs than needed, which the program could safely ignore (or warn about), it'll still exit with an error and an incorrect message.
The comparison should be updated to:
Usage: HappyToYou
Example: HappyToYou Birthday Bob
`
Few things are more frustrating than error messages that are uninformative or wrong because the former doesn't help you resolve the issue and the latter sends the user down the wrong path in trying to find a solution.
The comparison should be updated to:
if (argc Some inputs appear to be missing. Please enter the holiday and your name.Usage: HappyToYou
Example: HappyToYou Birthday Bob
`
Few things are more frustrating than error messages that are uninformative or wrong because the former doesn't help you resolve the issue and the latter sends the user down the wrong path in trying to find a solution.
Code Snippets
#include <stdio.h>
#include <error.h>
int main(int argc, char *argv[]) {
/* notice the logical operator update here; prevents bogus error
message if user provides more than 2 inputs */
if (argc < 3)
errx(1, "Give a holiday and a name as arguments.");
printf(
"Happy %1$s to you.\n"
"Happy %1$s to you.\n"
"Happy %1$s, dear %2$s!\n"
"Happy %1$s to you.\n",
argv[1],
argv[2]
);
return 0;
}Context
StackExchange Code Review Q#106487, answer score: 6
Revisions (0)
No revisions yet.