Handling Arguments in C++ not working - c++

I am using this code:
int handleArgs(int argc, char *argv[]) {
if(argc <= 1)
{return 0;}
else
{ // If no arguments, terminate, otherwise: handle args
for(int i=1; i<argc; i++) {
if (argv[i] == "-a" || argv[i] == "--admin")
{ // If admin argument
char *pwd = argv[i+1]; // i + 1 b/c we want the next argument; the password
if(pwd == "1729" || pwd == "GabeN")
{ // Verify Password
cout << "Sorry, console feature unavailable.\n" << endl;// Will replace with console function when I get to it
}
else
{
cout << "Wrong/No passkey, bruh.\n" << endl;
} // If the password is wrong
}
else if (argv[i] == "-v" || argv[i] == "--version")
{ // If user asks for version info
cout << "You are running\nDev0.0.0" << endl; // Tell the user the version
}
else if (argv[i]==" -h" || argv[i]=="--help")
{
cout << "Usage: " << argv[0] << " -[switch] argument(s)\n";
cout << " -a, --admin Open console view. Requires password\n";
cout << " -v, --version Print version and exit\n";
cout << " -h, --help Print this message and exit\n" << endl;
}
else {
cout << "Is you dumb?\n '" << argv[0] << " --help' for help" << endl; // Insult the user
}
}
}
return 1;
}
However, every time I give it an argument, I receive the invalid argument message (the last else statement):
Is you dumb?
'main --help' for help
I'm new to C++, and I have no idea what I am doing (wrong). Could anyone provide me with some helpful insights? Thanks
--FracturedCode

argv is an array of C-Strings (char*). You are using == and comparing memory addresses instead of the overloaded == operator that C++ strings provide. You should use strncmp to compare your strings (it's safer than strcmp). Although it doesn't matter much here as you are comparing with a literal, which guarantees one of them will end.

Related

Way to reduce else if statements when using string as condition

I'm making a terminal-like program (to calculate currency) with custom commands as input but I have a problem.
Every time I implement a new command, I have to add a new else if statement. This wouldn't be a problem but for a terminal-like program there can be a lot of commands.
Here is my code:
#include <iostream>
#include <string>
#include <Windows.h>
#include <math.h>
float user_balance = 0.0f;
float eur_in_czk = 24.0f; //ammount of czk in single euro
std::string currency = "czk";
bool czk_to_eur_enabled = true;
bool eur_to_czk_enabled = false;
//------------------START method definition---------------------------------------------------------
void czk_to_eur()
{
if (czk_to_eur_enabled) //to prevent using twice in a row
{
user_balance /= eur_in_czk;
user_balance = floorf(user_balance * 100) / 100; //limit to two decimal numbers
currency = "eur";
czk_to_eur_enabled = false;
eur_to_czk_enabled = true;
}
else
{
std::cout << "Your savings are already converted to " << currency << "!" << std::endl;
}
}
void eur_to_czk()
{
if (eur_to_czk_enabled) //to prevent using twice in a row
{
user_balance *= eur_in_czk;
user_balance = floorf(user_balance * 100) / 100; //limit to two decimal numbers
currency = "czk";
eur_to_czk_enabled = false;
czk_to_eur_enabled = true;
}
else
{
std::cout << "Your savings are already converted to " << currency << "!" << std::endl;
}
}
void set_balance(float new_balance)
{
user_balance = new_balance;
}
void add_balance(float new_balance)
{
user_balance += new_balance;
}
//------------------END method definition-----------------------------------------------------------
int main()
{
bool main_loop = true; //main loop enabler
float input_money;
std::string user_command = "";
std::cout << "This is currency converter v1.0 (czk to eur and back)\n\n\n" << std::endl;
while (main_loop) //main loop for currency converter
{
std::cout << "Input: ";
std::cin >> user_command;
std::cout << std::endl;
if ((user_command == "setbal") || (user_command == "SETBAL"))
{
std::cout << "Your balance is " << user_balance << " " << currency << ".\n";
std::cout << "Please enter desired value (" << currency << "): ";
std::cin >> input_money;
set_balance(input_money);
std::cout << "\n" << std::endl;
}
else if ((user_command == "addbal") || (user_command == "ADDBAL"))
{
std::cout << "Your balance is " << user_balance << " " << currency << ".\n";
std::cout << "Please enter desired value (" << currency << "): ";
std::cin >> input_money;
add_balance(input_money);
std::cout << "\n" << std::endl;
}
else if ((user_command == "balance") || (user_command == "BALANCE"))
{
std::cout << "Your balance is " << user_balance << " " << currency << "." << std::endl;
}
else if ((user_command == "curstat") || (user_command == "CURSTAT"))
{
std::cout << "Currency status is " << eur_in_czk << " czk in 1 eur." << std::endl;
}
else if ((user_command == "toeur") || (user_command == "TOEUR"))
{
czk_to_eur();
}
else if ((user_command == "toczk") || (user_command == "TOCZK"))
{
eur_to_czk();
}
else if ((user_command == "cheuv") || (user_command == "CHEUV"))
{
std::cout << "Change eur value (" << eur_in_czk << "): ";
std::cin >> eur_in_czk;
std::cout << std::endl;
}
else if ((user_command == "help") || (user_command == "HELP"))
{
std::cout << "SETBAL Sets balance.\n"
<< "ADDBAL Adds balance.\n"
<< "BALANCE Shows current balance.\n"
<< "CURSTAT Shows currency status.\n"
<< "TOEUR Converts czk to eur.\n"
<< "TOCZK Converts eur to czk.\n"
<< "CHEUV Changes eur currency value.\n"
<< "CLS Cleans terminal history.\n"
<< "EXIT Exits program.\n" << std::endl;
}
else if ((user_command == "cls") || (user_command == "CLS"))
{
system("CLS"); //funtion from Windows.h library
}
else if ((user_command == "exit") || (user_command == "EXIT"))
{
main_loop = false;
}
else
{
std::cout << "'" << user_command << "'"
<< "is not recognized as an internal or external command!\n";
std::cout << "Type 'HELP' to see available commands.\n" << std::endl;
}
}
return 0;
}
The bottom part of the code in while cycle is where the problem is.
Everything works fine but I would like to know, if there is any other way. And switch to my knowledge does not support string values as condition/dependency. (also I'm currently not using any custom classes and/or custom header files because this is just experiment.)
Is there any other way to do it?
Normally I would suggest using a std::map with a string as the key and a function as the value so that you could search the map for a command and then invoke the function associated with it. However, since that's already been mentioned in the comments I figured I'd get all fancy and provide a totally wack solution you probably shouldn't use.
This wack solution allows you to use string literals in a switch/case statement. This is possible by taking advantage of a feature of modern C++ called user defined literals that allow you to produce objects of user-defined type by defining a user-defined suffix much in the same way you append U to a integer literal to specify an unsigned value.
The first thing we'll do is define a user defined literal that produces a hash value that is calculated at compile time. Since this generates a hash value from the string it is possible to encounter collisions but that's dependant on the quality of the hash algorithm used. For our example we're going to use something simple. This following snippet defines a string literal with the suffix _C that generates our hash.
constexpr uint32_t djb2Hash(const char* str, int index = 0)
{
return !str[index]
? 0x1505
: (djb2Hash(str, index + 1) * 0x21) ^ str[index];
}
// Create a literal type for short-hand case strings
constexpr uint32_t operator"" _C(const char str[], size_t /*size*/)
{
return djb2Hash(str);
}
Now every time the compiler sees a string literal in the format of "Hello World"_C it will produce a hash value and use that in place of the string.
Now we'll apply this to your existing code. First we'll separate the code that takes the user command from cin and make the given command all lower case.
std::string get_command()
{
std::cout << "Input: ";
std::string user_command;
std::cin >> user_command;
std::cout << std::endl;
std::transform(
user_command.begin(),
user_command.end(),
user_command.begin(),
[](char ch) { return static_cast<char>(std::tolower(ch)); });
return user_command;
}
There now that we can get an all lowercase command from the user we need to process that so we'll take your original set of if/else statements and turn them into a simple switch/case statement instead. Now since we can't actually use string literals in the switch/case statement we'll have to fudge a little bit and generate the hash value of the users command for the switch part of the code. We'll also take all of your commands and add the _C suffix to them so that the compiler automatically generates our hash values for us.
int main()
{
bool main_loop = true; //main loop enabler
std::cout << "This is currency converter v1.0 (czk to eur and back)\n\n\n" << std::endl;
while (main_loop) //main loop for currency converter
{
const auto user_command(get_command());
switch(djb2Hash(user_command.c_str()))
{
case "setbal"_C:
std::cout << "Set balance command\n";
break;
case "addbal"_C:
std::cout << "Add balance command\n";
break;
case "balance"_C:
std::cout << "Get balance command\n";
break;
case "curstat"_C:
std::cout << "Get current status command\n";
break;
case "help"_C:
std::cout << "Get help command\n";
break;
case "exit"_C:
main_loop = false;
break;
default:
std::cout
<< "'" << user_command << "'"
<< "is not recognized as an internal or external command!\n"
<< "Type 'HELP' to see available commands.\n" << std::endl;
}
}
}
And there you have it. A totally wack solution! Now keep in mind that we're not really using strings in the switch/case statement, we're just hiding most of the details of generating hash values which are then used.

C++ std::logic_error within for loop using argv

I am new to C++ and I am trying to write a program to take in command line arguments and produce a .desktop file. I am trying to implement identification of the argv values but I keep getting a std::logic_error
My code is:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
string name;
string comment;
for(int i = 1; i <= argc; i++) {
char* tmp[] = {argv[i]};
string param = *tmp;
string paramVal = argv[i+1];
if(param == "-h") {
cout << "-h Display this help dialogue" << endl;
cout << "-n Set entry name" << endl;
cout << "-c Set entry comment" << endl;
cout << "-e Set entry executable path" << endl;
cout << "-i Set entry icon" << endl;
break;
}
else if(param == "-n") {
name = paramVal;
i++;
continue;
}
else if(param == "-c") {
comment = paramVal;
i++;
continue;
}
else if(param == "-e") {
}
else if(param == "-i") {
}
else {
cout << "ERROR >>> Unrecognised parameter %s" << param << endl;
}
}
cout << "Name: %s\nComment: %s" << name << comment << endl;
return(0);
}
The program compiles fine (using g++) but when I try to run ./createDesktopIcon -n a -c b I get the following error
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted
Please help as it is very frustrating
Here are the problems I see:
i <= argc
You want to compare i < argc because the argv[argc] element in the array is actually one past the last element in the argv array.
Also, here:
string paramVal = argv[i+1];
This will access the array out of bounds as well.
You might want to look at getopt to do all of this for you.

Simple Calculator using command line argument C++

I'm new to C++. I'm writing a simple calculator using command line. The command line should have this format:
programname firstNumber operator secondNumber
Here what I got so far:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
if (argc != 3)
{
cerr << "Usage: " << argv[0] << endl;
exit(0);
}
else
{
int firstNumber = atoi(argv[1]);
char theOperator = atoi(argv[2]);
int secondNumber = atoi(argv[3]);
switch (theOperator)
{
case'+':
{
cout << "The answer is " << firstNumber + secondNumber << endl;
break;
}
case '-':
{
cout << "The answer is " << firstNumber - secondNumber << endl;
break;
}
case '*':
{
cout << "The answer is " << firstNumber * secondNumber << endl;
break;
}
case '/':
{
if (secondNumber == 0)
{
cout << "Can not devide by a ZERO" << endl;
break;
}
else
{
cout << "The answer is " << firstNumber / secondNumber << endl;
break;
}
}
}
}
}
The program does not run. When I run it, it displays an appropriate usage message and end the program. Can anyone please help me?
Others have already given you the answer but you could have very easily figured this one out on your own. Just print what argc is at the point where you know the code is going into:
int main(int argc, char* argv[])
{
if (argc != 3)
{
cout << "argc is: " << argc << endl; // Debug output that you delete later
cerr << "Usage: " << argv[0] << endl;
exit(0);
}
else
And then come back with what argc is. When you find that argc is actually 4 and you want to know what is inside argc you should write some code to print it so that you can figure it out... Like this:
int main(int argc, char* argv[])
{
cout << "argc is: " << argc << endl; // Debug output that you delete later
for (int i = 0; i < argc; ++i)
{
// Print out all of the arguments since it's not working as you expect...
cout << "argv[" << i << "] = " << argv[i] << endl;
}
if (argc != 3)
{
cerr << "Usage: " << argv[0] << endl;
exit(0);
}
else
and you would have very quickly figured out what is wrong...
Please learn how to do this because it will save your but in the future and you won't have to wait for an answer here.
Additionally there is another error in your code.
Why on earth are you converting the + character from a string to an int?
else
{
int firstNumber = atoi(argv[1]);
char theOperator = atoi(argv[2]); // <<< WTF? Why?
int secondNumber = atoi(argv[3]);
switch (theOperator)
You probably want to get rid of the atoi part there and just go with:
char theOperator = argv[2][0]; // First character of the string
Provided that the second argument will always have only one letter... Which you might want to enforce/check. See strlen() and std::string and note that the type of argv[2] is char* (pointer to char).
I also recommend that you read How to debug small programs which is linked from the SO Howto-Ask Help Page. It may help a little. And no, I don't think your question is bad. Debugging small programs is a skill you'll need in the future if you intend to program so it will benefit you to learn it now.
Welcome to programming and C++ :)
The parameter argc also counts the program's name.
Try this:
if (argc != 4) // We expect 4 arguments: programname number operator number
{
cerr << "Usage: " << argv[0] << " <number> <operator> <number>" << endl;
exit(0);
}
In your code, running the program correctly (with all 3 parameters) displays the error message because argc equals 4.
If you type in
programname firstNumber operator secondNumber
You have 4 arguments, not 3.
argv[0] = programname
argv[1] = firstNumber
argv[2] = operator
argv[3] = secondNumber
Looks like your program is working correctly... at least as far as printing the usage message goes.
See also the other comments regarding your use of the operator argument.

c++ program won't output as expected

I'm writing a program to familiarize myself with input and command line arguments.
I'm trying to scan the user's input for either 'a' or 'b', and if it matches print the next argument given out. For some reason no matter what the user enters it always outputs as "Invalid." Can anyone see what I might be doing wrong?
int main(int argc, char* argv[])
{
if(argc != 5)
{ //checks if input is blank
cout << "Usage: <Function>, String, Usage: <Function>, String," << endl;
}
else
{
for(int i = 1; i<argc; i++)
{
cout << argv[i] << endl;
if(argv[i][1] == 'a')
{
cout << argv[i] << "ASCII" << endl;
}
if(argv[i][1] == 'b')
{
cout << argv[i] << "BINARY" << endl;
}
else
{
cout << "incorrect format" << endl;
}
}
}
}
argv[i][1] is the second character of the string argv[i] because arrays in C++ are zero-based.
I think you may want to use argv[i][0] instead, the first character.
See the following code for a sample:
#include <iostream>
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
std::cout << " Argument: " << argv[i] << '\n';
std::cout << " First: " << argv[i][0] << '\n';
}
return 0;
}
Running that as per the following transcript, gives the expected output:
pax> testprog alpha beta gamma delta epsilon
Argument: alpha
First: a
Argument: beta
First: b
Argument: gamma
First: g
Argument: delta
First: d
Argument: epsilon
First: e

Issue regarding size_t

If you go in my post history you'll see that i'm trying to develop an interpreter for a language that i'm working on. I want to use size_t using two different codes, but they all return nothing.
Here is the post of what i was trying: http://stackoverflow.com/questions/1215688/read-something-after-a-word-in-c
When i try to use the file that i'm testing it returns me nothing. Here is the sample file(only a print function that i'm trying to develop in my language):
print "This is a print function that i'm trying to develop in my language"
But remember that this is like print in Python, what the user type into the quotes(" ") is what have to be printed to all, remember that the user can choose what put into the quotes, then don't put something like a simple cout, post something that reads what is inside the quotes and print it to all. But here is the two test codes to do this, but all of they don't returns nothing to me:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main( int argc, char* argv[] )
{
// Error Messages
string extension = argv[ 1 ];
if(argc != 2)
{
cout << "Error syntax is incorrect!\nSyntax: " << argv[ 0 ] << " <file>\n";
return 0;
}
if(extension[extension.length()-3] != '.')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
if(extension[extension.length()-2] != 't')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
if(extension[extension.length()-1] != 'r')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
// End of the error messages
ifstream file(argv[ 1 ]);
if (!file.good()) {
cout << "File " << argv[1] << " does not exist.\n";
return 0;
}
string linha;
while (!file.eof())
{
getline(file, linha);
if (linha == "print")
{
size_t idx = linha.find("\""); //find the first quote on the line
while ( idx != string::npos ) {
size_t idx_end = linha.find("\"",idx+1); //end of quote
string quotes;
quotes.assign(linha,idx,idx_end-idx+1);
// do not print the start and end " strings
cout << "quotes:" << quotes.substr(1,quotes.length()-2) << endl;
//check for another quote on the same line
idx = linha.find("\"",idx_end+1);
}
}
}
return 0;
}
The second:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main( int argc, char* argv[] )
{
// Error Messages
string extension = argv[ 1 ];
if(argc != 2)
{
cout << "Error syntax is incorrect!\nSyntax: " << argv[ 0 ] << " <file>\n";
return 0;
}
if(extension[extension.length()-3] != '.')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
if(extension[extension.length()-2] != 't')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
if(extension[extension.length()-1] != 'r')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
// End of the error messages
ifstream file(argv[ 1 ]);
if (!file.good()) {
cout << "File " << argv[1] << " does not exist.\n";
return 0;
}
string linha;
while (!file.eof())
{
getline(file, linha);
if (linha == "print")
{
string code = " print \" hi \" ";
size_t beg = code.find("\"");
size_t end = code.find("\"", beg+1);
// end-beg-1 = the length of the string between ""
cout << code.substr(beg+1, end-beg-1);
}
}
return 0;
}
And here is what is printed in the console:
ubuntu#ubuntu-laptop:~/Desktop/Tree$ ./tree test.tr
ubuntu#ubuntu-laptop:~/Desktop/Tree$
Like i said, it prints me nothing.
See my post in D.I.C.: http://www.dreamincode.net/forums/showtopic118026.htm
Thanks,
Nathan Paulino Campos
Your problem is the line
if (linha == "print")
which assumes the entire line just read in is "print", not that the line STARTS with print.
Also, why would you use 3 separate checks for a .tr extension, vs. just checking the end of the filename for ".tr"? (You should also be checking that argv[1] is long enough before checking substrings...)
getline(file, linha) will read an entire line from the file, so linha never be equal to print.