Video Coming Soon...
40: echo
The echo command is probably the simplest command you could create. You just print the argv[]. That's it...or is it?
The Challenge
The complicated part of echo is the -e option, which tells echo to interpret any C/C++ control characters. That means if you do:
echo "\\thello"
You'll get \thello as output, but if you pass -e:
echo -e "\\thello"
It will read the \t and convert it to an actual TAB character just like in a string.
You'll notice I'm typing \\t and not \t. That's because the shell will already convert the \t for you. You can also use ' (single-quote) like this:
echo -e '\thello'
To do the same thing as "\\t".
The Code
My version of echo implements the -n parameter to get started, and so should yours. Then implement the -e option.
See my first version of echo
View Source file echo.cpp Only#include <fmt/core.h>
#include <string>
#include <unistd.h>
int main(int argc, char* argv[]) {
int opt = 0;
bool no_newline = false;
while((opt = getopt(argc, argv, "n")) != -1) {
switch(opt) {
case 'n':
no_newline = true;
break;
default:
fmt::println("USAGE: echo -n [text...]");
return 1;
}
}
for(int i = optind; i < argc; i++) {
fmt::print("{} ", argv[i]);
}
if(!no_newline) {
fmt::println("\n");
}
}
The Discussion
When you're doing parsing of a string like this it's best to use a switch statement to keep organized. But you don't have to use a switch. You could also use a unordered_map.
The unordered_map would definitely be slower, and for something simple like echo probably overkill. But, this would make it possible to load a configuration for your language of choice and translate any characters you want. Maybe your language doesn't use \t. With a switch you'd have to change the code.
Usually choosing configurable data over fast inflexible code is better. The best is fast and configurable with data.
Further Study
As mentioned, try using unordered_map to do the conversion.
Register for Learn C++ the Hard Way
Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.