/*
Функция принимает в качество аргумента строку, разделяет ее по "пробелу"
и возвращает вектор полученных слов
*/
std::vectorstd::string SplitString(const std::string& str) {
std::istringstream iss(str);
TEST(ArgParserTestSuite, HelpStringTest) {
ArgParser parser("My Parser");
parser.AddHelp('h', "help", "Some Description about program");
parser.AddStringArgument('i', "input", "File path for input file").MultiValue(1);
parser.AddFlag('s', "flag1", "Use some logic").Default(true);
parser.AddFlag('p', "flag2", "Use some logic");
parser.AddIntArgument("numer", "Some Number");
code
ASSERT_TRUE(parser.Parse(SplitString("app --help")));
// Проверка закоментирована намеренно. Ождиается, что результат вызова функции будет приблизительно такой же,
// но не с точностью до символа
/*ASSERT_EQ(
parser.HelpDescription(),
"My Parser\n"
"Some Description about program\n"
"\n"
"-i, --input=<string>, File path for input file [repeated, min args = 1]\n"
"-s, --flag1, Use some logic [default = true]\n"
"-p, --flag2, Use some logic\n"
" --number=<int>, Some Number\n"
"\n"
"-h, --help Display this help and exit\n"
);*/
}
9: Value of: parser.Parse(SplitString("app --param1=1 --param1=2 --param1=3"))
9: Actual: false
9: Expected: true
9: [ FAILED ] ArgParserTestSuite.MultiValueTest (0 ms)
9: [----------] 1 test from ArgParserTestSuite (0 ms total)
9:
9: [----------] Global test environment tear-down
9: [==========] 1 test from 1 test suite ran. (0 ms total)
9: [ PASSED ] 0 tests.
9: [ FAILED ] 1 test, listed below:
9: [ FAILED ] ArgParserTestSuite.MultiValueTest
9:
9: 1 FAILED TEST
why failed, fix it
Assistant
The unit test ArgParserTestSuite.MultiValueTest is failing because the library is unable to correctly handle multiple values for an integer argument. The specific problem lies within the ArgParser::Parse method, which does not seem to properly set multi_args_count_ for the integer argument or store its multiple values.
The provided code is complex, and the error message "Actual: false Expected: true" indicates that the Parse method returned false when it was expected to return true. The test case is designed to check if the Parse successfully processes multiple instances of an integer argument (--param1=1 --param1=2 --param1=3).
To debug this issue, you may need to review the logic in the ArgParser::Parse method that handles cases where all_[j]->GetTypeFlag() is TypeFlag::INT and the argument is flagged with GetFlagMultiValue(). This part of the code is responsible for incrementing multi_args_count_ and storing the values, both of which appear to be related to the failure.
Here are few points to investigate:
Ensure that the integer argument is correctly configured with the MultiValue flag.
Check if the GetIntValue function can handle retrieving values from a list of integers. In the failure message, GetIntValue("param1", 0) is used, but the actual GetIntValue function doesn't seem to support indexing. Therefore, that function might not behave as expected.
The ArgParser::Parse method might not be incrementing multi_args_count_ correctly for the Int argument when multiple values are passed.
The storing of multiple integer values may not be happening correctly. Ensure that the values are pushed into the appropriate vector.
Without more context or access to the full code base and the Arguments.h implementation, these are the initial areas to investigate. A thorough debugging session will be required to identify and fix the precise issue.
Since the code is complex and we only see parts of it, for a full review and fix, it would be best to ensure proper unit tests for each class and function are in place to isolate the behavior and ensure intended functionality.
The segmentation fault (also known as segfault) that occurs during the execution of your ArgParserTestSuite.MultiValueTest suggests that there is a memory access violation in your code. Segmentation faults are often due to attempting to read or write an illegal location in memory, such as dereferencing a null or uninitialized pointer, accessing memory that has been freed, or going out of the bounds of an array.
Looking at the provided code and test case snippets, there are several potential causes for the segmentation fault:
Undefined Behavior from Uninitialized Variables or Memory:
You're dynamically allocating various Args subclass instances (like Int, String, and Bool) with new and storing them as pointers in the all_ vector. This can be error-prone if not managed carefully. For example, if a function like GetIntValue tries to access an index (ind) in all_values_ that is out of bounds or if all_values_ has not been properly populated, it can lead to undefined behavior and a segfault.
Similarly, the store_values_ member in Args class is an uninitialized pointer. If the code attempts to dereference (*store_values_).push_back(value); without properly assigning it to a valid vector object, it will also cause a segfault.
Memory Leaks and Possible Dangling Pointers:
Dynamically allocated instances are not being deleted, which does not directly cause the segmentation fault, but shows that there might be memory management issues. In C++, raw pointers can easily become dangling (pointing to deallocated memory), which can later cause access violations.
Incorrect Type Casting:
The code is using static_cast to downcast Args* to more derived types like Int* or String*. If for some reason the actual object pointed to by Args* is not of the expected derived type, using static_cast will lead to undefined behavior and possibly a segfault when trying to access member functions or variables that do not exist for that object.
To debug and fix the segmentation fault, you can do the following:
Use Debugging Tools: Utilize a debugger (like gdb on Unix or Visual Studio Debugger on Windows) to find the exact line where the segfault occurs. A debugger will often point you directly to the problematic line, and you can inspect the call stack and variables to understand what went wrong.
The ASSERT_TRUE statement in your test ArgParserTestSuite.MultiValueTest is expecting the Parse function to return true when given the argument string "app --param1=1 --param1=2 --param1=3". If this ASSERT_TRUE check fails, it means that Parse is returning false.
From the code provided, it looks like the Parse function is meant to set multi_args_count_ correctly when the flag_multi_value_ is true for an argument. The Parse function will return false under the following conditions specific to multi_args_count_:
If the minimum number of required values (min_args_count_) for an argument that can have multiple values is higher than the number of values actually provided (multi_args_count_).
If the parsed count of arguments does not match the size of the all_ vector.
Let's look at the logic that handles multi-value arguments for INT in the Parse function:
cpp
if (all_[j]->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
//arg->AddAllValues(arg->GetValue());
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
//arg->AddAllValues(arg->GetValue());
}
}
As noted in the comments, the //arg->AddAllValues(arg->GetValue()); lines were probably meant to add values to the all_values_ vector in the Int class, but they are currently commented out. This is likely a mistake because without these lines, the values are not actually being stored anywhere, and the subsequent call to GetIntValue("param1", 0) would fail because there are no values in to return.
User
int ArgParser::GetIntValue(const std::string param, const int ind) {
if (static_cast<Int*>(all_values_[ind])->GetParam() == param) {
return static_cast<Int*>(all_[ind])->GetIndexedValue(ind);
}
}идентификатор "all_values_" не определенC/C++(20)
Assistant
The error message you're seeing:
code
идентификатор "all_values_" не определенC/C++(20)
translates to:
code
identifier "all_values_" is undefined C/C++(20)
This indicates that the code is trying to access an identifier all_values_ which has not been declared within the current scope or is not a member of the ArgParser class.
The method GetIntValue seems to be incorrectly referencing all_values_ when it should be referencing all_. There's also a logic issue in checking the parameter name against the wrong vector (all_values_ instead of all_). It should correctly reference all_ to find the Int argument object and then get the indexed value from that Int argument.
Below is a corrected version of the GetIntValue method:
cpp
int ArgParser::GetIntValue(const std::string param, const int ind) {
// Loop through all arguments to find the one with the matching parameter name
for (auto* arg : all_) {
if (arg->GetTypeFlag() == TypeFlag::INT) {
Int* intArg = static_cast<Int*>(arg);
if (intArg->GetParam() == param) {
// Check if the requested index is within the bounds of all_values_
if (ind >= 0 && ind < intArg->all_values_.size()) {
return intArg->GetIndexedValue(ind); // Get the value at the specified index
} else {
// Handle the out-of-bounds index, e.g., throw an exception or return a default value
throw std::out_of_range("Index is out of range for argument: " + param);
}
}
}
}
// Handle the case where the parameter is not found
throw std::invalid_argument("Parameter not found: " + param);
}
In the above implementation, we iterate through the all_ vector, looking for an Int argument that has the same param as the one provided to the function. When found, we use the GetIntValue method of the Int class, making sure to first check whether the provided index is within bounds of the all_values_ vector stored in that Int object.
Please note that I added checks for out-of-range indices and throw exceptions if necessary. Depending on your code structure and the manner in which you handle error cases, you could handle the out-of-range index differently, for example, by providing a sentinel value or by ensuring that your logic elsewhere prevents such cases.
Segmentation faults are typically caused by dereferencing a null or invalid pointer, accessing memory that the program does not have the rights to access, or using an uninitialized pointer. Given that your ArgParserTestSuite.MultiValueTest is still encountering a segfault, let's go through some possible issues that might be causing this:
Dereferencing null or invalid pointers: Check all instances where pointers are being dereferenced. Make sure that the pointers are pointing to valid objects before they are used. For example, in GetIntValue(const std::string param, const int ind) make sure that each static cast is safe.
Uninitialized variables: Ensure that all data members of the classes are properly initialized, either in the constructor or by default.
Out-of-bounds vector access: The error might occur during an attempt to access an index of all_ or all_values_ that is out of bounds. Check for any such case, ideally by using .at(ind) instead of [ind] for vectors, as .at(ind) does bounds checking and throws an exception if the index is out of range.
Lifetime of objects stored in the all_ vector: Ensure that the objects pointed by the all_ vector are still valid (not deleted) when they are accessed.
It's not clear which part of the code is leading to the segmentation fault, but here is a step-by-step guide to debug this type of error:
Use a debugger tool like gdb or lldb to find the exact line of code causing the segfault.
Use the debugger's backtrace (bt in gdb, bt or thread backtrace in lldb) command to see the function call stack at the point where the segfault occurs.
Inspect the involved variables to check for unexpected values.
Add debug print statements around the suspected lines of code to verify the program's flow and the values of variables.
Once you've narrowed down the issue, apply checks or refactor the code to properly manage object lifetimes, handle all possible paths that pointers can take, and ensure no out-of-bound accesses occur.
Unfortunately, without the ability to debug in my environment, I can't provide a specific line or fix. Nevertheless, following the above steps should help you identify and solve the issue.
User
ASSERT_TRUE(parser.Parse(SplitString("app --param1=1 --param1=2 --param1=3"))); why it doesn't parse it #include "ArgParser.h"
#include "Arguments.h"
#include
#include
#include
namespace ArgumentParser {
code
Assistant
The issue you're facing with the ArgParser::Parse method not correctly parsing the input "app --param1=1 --param1=2 --param1=3" and returning false could be due to several reasons.
Let's break down the multiple things that could be wrong, based on the code snippets provided:
Incorrect Handling of MultiValue Arguments:
With the provided code, when you add an Int argument with MultiValue, you expect it to handle multiple instances of the same argument. Nevertheless, there might be a logic issue in counting the successful parses.
Complex Logic Flow in Parse Method:
The Parse method's logic is intricate and prone to mistakes. The counters for parsed arguments (such as count and multi_args_count_) make the method susceptible to errors.
False Returns Despite Correct Parsing:
It might be the case that parsing was actually successful, but due to the incorrect logic in the checks following the parsing loop, false was returned instead.
Ambiguity with Positional Arguments:
The code for positional arguments within the Parse method might be interfering with regular parsing. It seems to increase the count variable without regard to whether the argument has already been counted.
Missing Code for Handling MinArgsCount:
The check for GetMinArgsCount() being greater than GetMultiArgsCount() returns false. There might be a missing setup code in your tests where the minimum argument count is set correctly for multi-value arguments.
To begin debugging, consider the following steps:
Comment out the return false; statement after checking the GetMinArgsCount() and GetMultiArgsCount() to see if that's where the logic is failing.
Add debugging statements before every incrementation of count, multi_args_count_, or anywhere false is returned to track what's happening inside the Parse method.
Check the AddIntArgument and MultiValue() methods to ensure they set up arguments correctly in terms of multi-value handling.
Additionally, there is an apparent issue with the GetIntValue(const std::string param, const int ind) method. It is attempting to loop through and performs a direct index access on without checking if is within the bounds of . It should be checking instead, which stores the actual values.
The ASSERT_EQ statement is expecting that the second element of int_values should be 2, as set with the call to StoreValues in the line parser.AddIntArgument('p', "param1").MultiValue().StoreValues(int_values);.
However, the test fails because the second element of int_values is not 2. The error might occur because the AddStoreValues function in Int class is not being called or is not working correctly. It's meant to push the values into the store_values_ vector, but if the vector is empty or does not contain the expected values, the assertion will fail.
There could be several issues within ArgParser::Parse, Int::AddStoreValues, or Int::AddAllValues methods that lead to this problem:
Incorrect Indexing: In C++, vectors are zero-indexed, so the first element has index 0, the second element has index 1, etc. If somewhere in the code the indexing is not being handled properly (e.g., expecting one-based indexing), the expected value might end up in the wrong index.
Pushing Values: Make sure that the value 2 is actually being pushed into the store_values_ vector. Inspect the AddStoreValues method to confirm that it does what it's supposed to do. The int_values vector should be the same as store_values_ and should be populated properly whenever Int::AddStoreValues is called.
Parsing Logic: Ensure that the parsing logic actually parses all occurrences of the --param1 option and that it's correctly pushing values into the all_values_ vector in the appropriate Int object which has store_values_ pointing to int_values.
Test Setup: Check whether the test setup correctly matches how the Parse method operates. Confirm that the Int argument is set up to accept multiple values and that store_values_ is set to reference the int_values vector before the parsing begins.
To debug this, you would follow these steps:
Add logging statements to the Int::AddStoreValues and Int::AddAllValues methods to ensure they are being called with the correct values.
Check if the MultiArgsCount method increases the count correctly for each value parsed.
}9: Test command: /Users/alishashelby/Desktop/labwork4-alishashelby/build/tests/argparser_tests "--gtest_filter=ArgParserTestSuite.MultiValueTest" "--gtest_also_run_disabled_tests"
9: Working Directory: /Users/alishashelby/Desktop/labwork4-alishashelby/build/tests
9: Test timeout computed to be: 10000000
9: Running main() from /Users/alishashelby/Desktop/labwork4-alishashelby/build/_deps/googletest-src/googletest/src/gtest_main.cc
9: Note: Google Test filter = ArgParserTestSuite.MultiValueTest
9: [==========] Running 1 test from 1 test suite.
9: [----------] Global test environment set-up.
9: [----------] 1 test from ArgParserTestSuite
9: [ RUN ] ArgParserTestSuite.MultiValueTest
9/15 Test #9: ArgParserTestSuite.MultiValueTest ...........***Exception: SegFault 0.00 sec
why segfault : 9 - ArgParserTestSuite.MultiValueTest (SEGFAULT)
Check for Invalid Accesses: Verify that all accessed indexes are within the bounds of their respective arrays and vectors, and all pointers are checked for nullptr before dereferencing.
Memory Management: Ensure that memory allocated with new is appropriately paired with delete to prevent leaks. Better yet, consider using smart pointers (std::unique_ptr or std::shared_ptr) to automate memory management and avoid manual deletion.
Safe Casting: Use dynamic_cast instead of static_cast when downcasting from base to derived to ensure the cast is valid. dynamic_cast will return nullptr if the cast is invalid, allowing you to check for success and avoid undefined behavior.
Reviewing the code thoroughly and addressing these points should help you eliminate the segmentation fault in your test case.
bool ArgParser::Parse(std::vector<std::string> args) {
if (all_.empty() && args.size() == 1) {
return true;
}
int count = 0;
for (int i = 0; i < args.size(); ++i) {
for (int j = 0; j < all_.size(); ++j) {
TypeFlag type = all_[j]->GetTypeFlag();
switch (type) {
case TypeFlag::INT: {
Int* arg = static_cast<Int*>(all_[j]);
std::string origin_param = "--" + arg->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(arg->GetShortParam());
origin_short_param += "=";
if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
++count;
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
++count;
} else if (all_[j]->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
//arg->AddAllValues(arg->GetValue());
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
//arg->AddAllValues(arg->GetValue());
}
}
if (all_[j]->GetFlagPositional()) {
int count_len = 0;
for (int k = 0; k < args[i].length(); ++k) {
if (!std::isdigit(args[i][k])){
break;
} else {
++count_len;
}
}
if (count_len == args[i].length()) {
arg->PutValue(args[i]);
arg->MultiArgsCount();
if (arg->GetFlagStoreValues()) {
arg->AddStoreValues(arg->GetValue());
arg->AddAllValues(arg->GetValue());
}
}
}
}
break;
case TypeFlag::STRING: {
String* arg = static_cast<String*>(all_[j]);
std::string origin_param = "--" + arg->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(arg->GetShortParam());
origin_short_param += "=";
if (args.size() == 1 && !arg->GetDefaultValue().empty()) {
arg->PutValue(arg->GetDefaultValue());
++count;
} else if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
if (arg->GetFlagStoreValue()) {
arg->AddStoreValue(arg->GetValue());
}
++count;
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
if (arg->GetFlagStoreValue()) {
arg->AddStoreValue(arg->GetValue());
}
++count;
} else if (arg->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
arg->MultiArgsCount();
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
arg->MultiArgsCount();
}
}
}
break;
case TypeFlag::BOOL: {
Bool* arg = static_cast<Bool*>(all_[j]);
std::string origin_flag = "--" + arg->GetFlag();
if (arg->GetIsFlag()) {
if (args[i].substr(0, origin_flag.length()) == origin_flag) {
if (arg->GetFlagStoreFlag()) {
arg->AddStoreFlag(true);
}
++count;
} else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) {
for (int z = 1; z < args[i].length(); ++z) {
if (args[i][z] == arg->GetShortFlag()) {
if (arg->GetFlagStoreFlag()) {
arg->AddStoreFlag(true);
}
++count;
}
}
}
}
}
break;
case TypeFlag::UNKNOWN: {
std::string origin_help = "--" + all_[j]->GetHelp();
std::string origin_short_help = "-";
origin_short_help.push_back(all_[j]->GetShortHelp());
if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) {
all_[j]->FlagHelp();
++count;
}
}
break;
}
}
}
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetMultiArgsCount() > 0) {
++count;
}
if (static_cast<Bool*>(all_[i])->GetFlagDefaultFlag()) {
++count;
}
if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) {
return false;
}
}
if (count == all_.size()) {
return true;
} else {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetFlagHelp()) {
return true;
}
}
return false;
}
}
String& ArgParser::AddStringArgument(const std::string param) {
String* str = new String();
str->param_ = param;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
str->Description(description);
return *str;
}
std::string ArgParser::GetStringValue(const std::string param) {
for (int i = 0; i < (all_).size(); ++i) {
if (static_cast<String*>(all_[i])->param_ == param) {
return static_cast<String*>(all_[i])->GetValue();
}
}
}
Int& ArgParser::AddIntArgument(const std::string number) {
Int* int_val = new Int();
int_val->param_ = number;
all_.push_back(int_val);
return *int_val;
}
Int& ArgParser::AddIntArgument(const std::string number, const std::string description) {
Int* int_val = new Int();
int_val->param_ = number;
all_.push_back(int_val);
int_val->Description(description);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Int*>(all_[i])->GetParam() == param) {
int value = std::stoi(static_cast<Int*>(all_[i])->GetValue());
return value;
}
}
}
Int& ArgParser::AddIntArgument(const char short_param, const std::string param) {
Int* int_val = new Int();
int_val->short_param_ = short_param;
int_val->param_ = param;
all_.push_back(int_val);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param, const int ind) {
if (static_cast<Int*>(all_[ind])->GetParam() == param) {
return static_cast<Int*>(all_[ind])->GetIndexedValue(ind);
}
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
return *new_flag;
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
Bool& ArgParser::AddFlag(const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlag(flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
bool ArgParser::GetFlag(const std::string flag) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Bool*>(all_[i])->GetFlag() == flag) {
return true;
}
}
return false;
}
bool ArgParser::Help() {
return true;
}
Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) {
Args* new_help = new Args();
new_help->Help(short_help, help);
new_help->Description(description);
all_.push_back(new_help);
return *new_help;
}
std::string ArgParser::HelpDescription() {
std::cout << "My Parser\n";
std::cout << "Some Description about program\n\n";
std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n";
std::cout << "-s, --flag1, Use some logic [default = true]\n";
std::cout << "-p, --flag2, Use some logic\n";
std::cout << " --number=<int>, Some Number\n\n";
std::cout << "-h, --help Display this help and exit\n";
}
}
#pragma once
#include
#include
namespace ArgumentParser {
enum class TypeFlag {
INT,
STRING,
BOOL,
UNKNOWN // In case no flag is set or Args is a base type that should not be instantiated
};
} why this line ASSERT_TRUE(parser.Parse(SplitString("app --param1=1 --param1=2 --param1=3"))); fails
all_values_
However, the test case should still fail even with the AddAllValues lines uncommented because the second condition mentioned above would not be satisfied due to an incorrect logic in counting when min_args_count_ is not satisfied.
To fix this issue and make the test pass:
Uncomment the arg->AddAllValues(arg->GetValue()); lines in the Parse function to ensure that multiple values are stored in all_values_.
Ensure that when multi_args_count_ is being increased, it corresponds to a valid argument. Also, make sure the min_args_count_ and multi_args_count_ comparison logic is correct.
Look for any other conditions that can cause Parse to return false when it should return true.
Verify the logic for storing the parsed Int values into the provided std::vector<int> using StoreValues is correctly implemented.
Make sure that the GetIntValue() methods work correctly. Specifically, the version that uses an index seems to be attempting to access a value in all_values_, which is a member variable of Int. There is a problem, though: GetIntValue() does not ensure that the indexed access into all_values_ is within bounds, which can lead to undefined behavior or a crash if the index is out of bounds.
Make these changes, and the test should hopefully pass. If it still fails, you need to reexamine the Parse method's logic, use a debugger to identify where it is failing, and ensure all logic paths are functioning as intended.
Finally, ensure you properly manage dynamically allocated memory by deleting the objects in the destructor of ArgParser to avoid memory leaks. Consider using smart pointers for safer memory management.
bool ArgParser::Parse(std::vector<std::string> args) {
if (all_.empty() && args.size() == 1) {
return true;
}
int count = 0;
for (int i = 0; i < args.size(); ++i) {
for (int j = 0; j < all_.size(); ++j) {
TypeFlag type = all_[j]->GetTypeFlag();
switch (type) {
case TypeFlag::INT: {
Int* arg = static_cast<Int*>(all_[j]);
std::string origin_param = "--" + arg->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(arg->GetShortParam());
origin_short_param += "=";
if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
++count;
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
++count;
} else if (all_[j]->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
arg->AddAllValues(arg->GetValue());
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
arg->AddAllValues(arg->GetValue());
}
}
if (all_[j]->GetFlagPositional()) {
int count_len = 0;
for (int k = 0; k < args[i].length(); ++k) {
if (!std::isdigit(args[i][k])){
break;
} else {
++count_len;
}
}
if (count_len == args[i].length()) {
arg->PutValue(args[i]);
arg->MultiArgsCount();
if (arg->GetFlagStoreValues()) {
arg->AddStoreValues(arg->GetValue());
arg->AddAllValues(arg->GetValue());
}
}
}
}
break;
case TypeFlag::STRING: {
String* arg = static_cast<String*>(all_[j]);
std::string origin_param = "--" + arg->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(arg->GetShortParam());
origin_short_param += "=";
if (args.size() == 1 && !arg->GetDefaultValue().empty()) {
arg->PutValue(arg->GetDefaultValue());
++count;
} else if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
if (arg->GetFlagStoreValue()) {
arg->AddStoreValue(arg->GetValue());
}
++count;
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
if (arg->GetFlagStoreValue()) {
arg->AddStoreValue(arg->GetValue());
}
++count;
} else if (arg->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
arg->MultiArgsCount();
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
arg->MultiArgsCount();
}
}
}
break;
case TypeFlag::BOOL: {
Bool* arg = static_cast<Bool*>(all_[j]);
std::string origin_flag = "--" + arg->GetFlag();
if (arg->GetIsFlag()) {
if (args[i].substr(0, origin_flag.length()) == origin_flag) {
if (arg->GetFlagStoreFlag()) {
arg->AddStoreFlag(true);
}
++count;
} else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) {
for (int z = 1; z < args[i].length(); ++z) {
if (args[i][z] == arg->GetShortFlag()) {
if (arg->GetFlagStoreFlag()) {
arg->AddStoreFlag(true);
}
++count;
}
}
}
}
}
break;
case TypeFlag::UNKNOWN: {
std::string origin_help = "--" + all_[j]->GetHelp();
std::string origin_short_help = "-";
origin_short_help.push_back(all_[j]->GetShortHelp());
if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) {
all_[j]->FlagHelp();
++count;
}
}
break;
}
}
}
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetMultiArgsCount() > 0) {
++count;
}
if (static_cast<Bool*>(all_[i])->GetFlagDefaultFlag()) {
++count;
}
if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) {
return false;
}
}
if (count == all_.size()) {
return true;
} else {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetFlagHelp()) {
return true;
}
}
return false;
}
}
String& ArgParser::AddStringArgument(const std::string param) {
String* str = new String();
str->param_ = param;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
str->Description(description);
return *str;
}
std::string ArgParser::GetStringValue(const std::string param) {
for (int i = 0; i < (all_).size(); ++i) {
if (static_cast<String*>(all_[i])->param_ == param) {
return static_cast<String*>(all_[i])->GetValue();
}
}
}
Int& ArgParser::AddIntArgument(const std::string number) {
Int* int_val = new Int();
int_val->param_ = number;
all_.push_back(int_val);
return *int_val;
}
Int& ArgParser::AddIntArgument(const std::string number, const std::string description) {
Int* int_val = new Int();
int_val->param_ = number;
all_.push_back(int_val);
int_val->Description(description);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Int*>(all_[i])->GetParam() == param) {
int value = std::stoi(static_cast<Int*>(all_[i])->GetValue());
return value;
}
}
}
Int& ArgParser::AddIntArgument(const char short_param, const std::string param) {
Int* int_val = new Int();
int_val->short_param_ = short_param;
int_val->param_ = param;
all_.push_back(int_val);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param, const int ind) {
// Loop through all arguments to find the one with the matching parameter name
for (auto* arg : all_) {
if (arg->GetTypeFlag() == TypeFlag::INT) {
Int* intArg = static_cast<Int*>(arg);
if (intArg->GetParam() == param) {
// Check if the requested index is within the bounds of all_values_
if (ind >= 0 && ind < intArg->all_values_.size()) {
return intArg->GetIndexedValue(ind); // Get the value at the specified index
} else {
// Handle the out-of-bounds index, e.g., throw an exception or return a default value
throw std::out_of_range("Index is out of range for argument: " + param);
}
}
}
}
// Handle the case where the parameter is not found
throw std::invalid_argument("Parameter not found: " + param);
}
code
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
return *new_flag;
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
Bool& ArgParser::AddFlag(const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlag(flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
bool ArgParser::GetFlag(const std::string flag) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Bool*>(all_[i])->GetFlag() == flag) {
return true;
}
}
return false;
}
bool ArgParser::Help() {
return true;
}
Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) {
Args* new_help = new Args();
new_help->Help(short_help, help);
new_help->Description(description);
all_.push_back(new_help);
return *new_help;
}
std::string ArgParser::HelpDescription() {
std::cout << "My Parser\n";
std::cout << "Some Description about program\n\n";
std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n";
std::cout << "-s, --flag1, Use some logic [default = true]\n";
std::cout << "-p, --flag2, Use some logic\n";
std::cout << " --number=<int>, Some Number\n\n";
std::cout << "-h, --help Display this help and exit\n";
}
}
still 9 - ArgParserTestSuite.MultiValueTest (SEGFAULT)
bool ArgParser::Parse(std::vector<std::string> args) {
if (all_.empty() && args.size() == 1) {
return true;
}
int count = 0;
for (int i = 0; i < args.size(); ++i) {
for (int j = 0; j < all_.size(); ++j) {
TypeFlag type = all_[j]->GetTypeFlag();
switch (type) {
case TypeFlag::INT: {
Int* arg = static_cast<Int*>(all_[j]);
std::string origin_param = "--" + arg->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(arg->GetShortParam());
origin_short_param += "=";
if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
++count;
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
++count;
} else if (all_[j]->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
arg->AddAllValues(arg->GetValue());
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
arg->AddAllValues(arg->GetValue());
}
}
if (all_[j]->GetFlagPositional()) {
int count_len = 0;
for (int k = 0; k < args[i].length(); ++k) {
if (!std::isdigit(args[i][k])){
break;
} else {
++count_len;
}
}
if (count_len == args[i].length()) {
arg->PutValue(args[i]);
arg->MultiArgsCount();
if (arg->GetFlagStoreValues()) {
arg->AddStoreValues(arg->GetValue());
arg->AddAllValues(arg->GetValue());
}
}
}
}
break;
case TypeFlag::STRING: {
String* arg = static_cast<String*>(all_[j]);
std::string origin_param = "--" + arg->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(arg->GetShortParam());
origin_short_param += "=";
if (args.size() == 1 && !arg->GetDefaultValue().empty()) {
arg->PutValue(arg->GetDefaultValue());
++count;
} else if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
if (arg->GetFlagStoreValue()) {
arg->AddStoreValue(arg->GetValue());
}
++count;
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
if (arg->GetFlagStoreValue()) {
arg->AddStoreValue(arg->GetValue());
}
++count;
} else if (arg->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
arg->MultiArgsCount();
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
arg->MultiArgsCount();
}
}
}
break;
case TypeFlag::BOOL: {
Bool* arg = static_cast<Bool*>(all_[j]);
std::string origin_flag = "--" + arg->GetFlag();
if (arg->GetIsFlag()) {
if (args[i].substr(0, origin_flag.length()) == origin_flag) {
if (arg->GetFlagStoreFlag()) {
arg->AddStoreFlag(true);
}
++count;
} else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) {
for (int z = 1; z < args[i].length(); ++z) {
if (args[i][z] == arg->GetShortFlag()) {
if (arg->GetFlagStoreFlag()) {
arg->AddStoreFlag(true);
}
++count;
}
}
}
}
}
break;
case TypeFlag::UNKNOWN: {
std::string origin_help = "--" + all_[j]->GetHelp();
std::string origin_short_help = "-";
origin_short_help.push_back(all_[j]->GetShortHelp());
if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) {
all_[j]->FlagHelp();
++count;
}
}
break;
}
}
}
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetMultiArgsCount() > 0) {
++count;
}
if (static_cast<Bool*>(all_[i])->GetFlagDefaultFlag()) {
++count;
}
if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) {
return false;
}
}
if (count == all_.size()) {
return true;
} else {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetFlagHelp()) {
return true;
}
}
return false;
}
}
String& ArgParser::AddStringArgument(const std::string param) {
String* str = new String();
str->param_ = param;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
str->Description(description);
return *str;
}
std::string ArgParser::GetStringValue(const std::string param) {
for (int i = 0; i < (all_).size(); ++i) {
if (static_cast<String*>(all_[i])->param_ == param) {
return static_cast<String*>(all_[i])->GetValue();
}
}
}
Int& ArgParser::AddIntArgument(const std::string number) {
Int* int_val = new Int();
int_val->param_ = number;
all_.push_back(int_val);
return *int_val;
}
Int& ArgParser::AddIntArgument(const std::string number, const std::string description) {
Int* int_val = new Int();
int_val->param_ = number;
all_.push_back(int_val);
int_val->Description(description);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Int*>(all_[i])->GetParam() == param) {
int value = std::stoi(static_cast<Int*>(all_[i])->GetValue());
return value;
}
}
}
Int& ArgParser::AddIntArgument(const char short_param, const std::string param) {
Int* int_val = new Int();
int_val->short_param_ = short_param;
int_val->param_ = param;
all_.push_back(int_val);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param, const int ind) {
// Loop through all arguments to find the one with the matching parameter name
for (auto* arg : all_) {
if (arg->GetTypeFlag() == TypeFlag::INT) {
Int* intArg = static_cast<Int*>(arg);
if (intArg->GetParam() == param) {
// Check if the requested index is within the bounds of all_values_
if (ind >= 0 && ind < intArg->all_values_.size()) {
return intArg->GetIndexedValue(ind); // Get the value at the specified index
}
}
}
}
}
code
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
return *new_flag;
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
Bool& ArgParser::AddFlag(const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlag(flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
bool ArgParser::GetFlag(const std::string flag) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Bool*>(all_[i])->GetFlag() == flag) {
return true;
}
}
return false;
}
bool ArgParser::Help() {
return true;
}
Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) {
Args* new_help = new Args();
new_help->Help(short_help, help);
new_help->Description(description);
all_.push_back(new_help);
return *new_help;
}
std::string ArgParser::HelpDescription() {
std::cout << "My Parser\n";
std::cout << "Some Description about program\n\n";
std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n";
std::cout << "-s, --flag1, Use some logic [default = true]\n";
std::cout << "-p, --flag2, Use some logic\n";
std::cout << " --number=<int>, Some Number\n\n";
std::cout << "-h, --help Display this help and exit\n";
}
}
all_
ind
ind
all_
all_values_
Finally, the overall design with raw pointers and manual memory management in modern C++ is risky and can easily produce segmentation faults and memory leaks. I strongly recommend changing the design to use smart pointers (std::unique_ptr or std::shared_ptr) which are managed automatically and go out of scope without the risk of memory mishandling.
Run the unit test with a debugger such as gdb and inspect the application state when false is returned. Correct the logic based on what you can glean from debugging and by adding relevant checks and corrections in the Parse method.
bool ArgParser::Parse(std::vector<std::string> args) {
if (all_.empty() && args.size() == 1) {
return true;
}
int count = 0;
for (int i = 0; i < args.size(); ++i) {
for (int j = 0; j < all_.size(); ++j) {
TypeFlag type = all_[j]->GetTypeFlag();
switch (type) {
case TypeFlag::INT: {
Int* arg = static_cast<Int*>(all_[j]);
std::string origin_param = "--" + arg->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(arg->GetShortParam());
origin_short_param += "=";
if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
++count;
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
++count;
} else if (all_[j]->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
arg->AddAllValues(arg->GetValue());
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
all_[j]->MultiArgsCount();
arg->AddAllValues(arg->GetValue());
}
}
}
break;
case TypeFlag::STRING: {
String* arg = static_cast<String*>(all_[j]);
std::string origin_param = "--" + arg->GetParam() + "=";
std::string origin_short_param = "-";
origin_short_param.push_back(arg->GetShortParam());
origin_short_param += "=";
if (args.size() == 1 && !arg->GetDefaultValue().empty()) {
arg->PutValue(arg->GetDefaultValue());
++count;
} else if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
if (arg->GetFlagStoreValue()) {
arg->AddStoreValue(arg->GetValue());
}
++count;
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
if (arg->GetFlagStoreValue()) {
arg->AddStoreValue(arg->GetValue());
}
++count;
} else if (arg->GetFlagMultiValue()) {
if (args[i].substr(0, origin_param.length()) == origin_param) {
arg->PutValue(args[i].substr(origin_param.length(), args[i].length()));
arg->MultiArgsCount();
} else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) {
arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length()));
arg->MultiArgsCount();
}
}
}
break;
case TypeFlag::BOOL: {
Bool* arg = static_cast<Bool*>(all_[j]);
std::string origin_flag = "--" + arg->GetFlag();
if (arg->GetIsFlag()) {
if (args[i].substr(0, origin_flag.length()) == origin_flag) {
if (arg->GetFlagStoreFlag()) {
arg->AddStoreFlag(true);
}
++count;
} else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) {
for (int z = 1; z < args[i].length(); ++z) {
if (args[i][z] == arg->GetShortFlag()) {
if (arg->GetFlagStoreFlag()) {
arg->AddStoreFlag(true);
}
++count;
}
}
}
}
}
break;
case TypeFlag::UNKNOWN: {
std::string origin_help = "--" + all_[j]->GetHelp();
std::string origin_short_help = "-";
origin_short_help.push_back(all_[j]->GetShortHelp());
if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) {
all_[j]->FlagHelp();
++count;
}
}
break;
}
if (all_[j]->GetFlagPositional()) {
int count_len = 0;
for (int k = 0; k < args[i].length(); ++k) {
if (!std::isdigit(args[i][k])){
break;
} else {
++count_len;
}
}
if (count_len == args[i].length()) {
static_cast<Int*>(all_[j])->PutValue(args[i]);
all_[j]->MultiArgsCount();
if (all_[j]->GetFlagStoreValues()) {
static_cast<Int*>(all_[j])->AddStoreValues(static_cast<Int*>(all_[j])->GetValue());
static_cast<Int*>(all_[j])->AddAllValues(static_cast<Int*>(all_[j])->GetValue());
}
}
}
}
}
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetMultiArgsCount() > 0) {
++count;
}
if (static_cast<Bool*>(all_[i])->GetFlagDefaultFlag()) {
++count;
}
if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) {
return false;
}
}
if (count == all_.size()) {
return true;
} else {
for (int i = 0; i < all_.size(); ++i) {
if (all_[i]->GetFlagHelp()) {
return true;
}
}
return false;
}
}
String& ArgParser::AddStringArgument(const std::string param) {
String* str = new String();
str->param_ = param;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
return *str;
}
String& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) {
String* str = new String();
str->short_param_ = short_param;
str->param_ = param;
str->flag_short_param_ = true;
all_.push_back(str);
str->Description(description);
return *str;
}
std::string ArgParser::GetStringValue(const std::string param) {
for (int i = 0; i < (all_).size(); ++i) {
if (static_cast<String*>(all_[i])->param_ == param) {
return static_cast<String*>(all_[i])->GetValue();
}
}
}
Int& ArgParser::AddIntArgument(const std::string number) {
Int* int_val = new Int();
int_val->param_ = number;
all_.push_back(int_val);
return *int_val;
}
Int& ArgParser::AddIntArgument(const std::string number, const std::string description) {
Int* int_val = new Int();
int_val->param_ = number;
all_.push_back(int_val);
int_val->Description(description);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Int*>(all_[i])->GetParam() == param) {
int value = std::stoi(static_cast<Int*>(all_[i])->GetValue());
return value;
}
}
}
Int& ArgParser::AddIntArgument(const char short_param, const std::string param) {
Int* int_val = new Int();
int_val->short_param_ = short_param;
int_val->param_ = param;
all_.push_back(int_val);
return *int_val;
}
int ArgParser::GetIntValue(const std::string param, const int ind) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Int*>(all_[i])->GetParam() == param) {
return static_cast<Int*>(all_[i])->GetIndexedValue(ind);
}
}
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
return *new_flag;
}
Bool& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlags(short_flag, flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
Bool& ArgParser::AddFlag(const std::string flag, const std::string description) {
Bool* new_flag = new Bool();
new_flag->AddFlag(flag);
all_.push_back(new_flag);
new_flag->Description(description);
return *new_flag;
}
bool ArgParser::GetFlag(const std::string flag) {
for (int i = 0; i < all_.size(); ++i) {
if (static_cast<Bool*>(all_[i])->GetFlag() == flag) {
return true;
}
}
return false;
}
bool ArgParser::Help() {
return true;
}
Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) {
Args* new_help = new Args();
new_help->Help(short_help, help);
new_help->Description(description);
all_.push_back(new_help);
return *new_help;
}
std::string ArgParser::HelpDescription() {
std::cout << "My Parser\n";
std::cout << "Some Description about program\n\n";
std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n";
std::cout << "-s, --flag1, Use some logic [default = true]\n";
std::cout << "-p, --flag2, Use some logic\n";
std::cout << " --number=<int>, Some Number\n\n";
std::cout << "-h, --help Display this help and exit\n";
}
Ensure the store_values_ vector of Int object is pointing to int_values before Parse is called.
Use a debugger to step through the Parse function and track the values that are being stored.
As a side note, I observe that your design relies heavily on raw pointers, casting, and manual memory management. There's a risk that if not structured correctly, your application could be suffering from undefined behavior. To make debugging easier and to follow better C++ practices, consider using std::unique_ptr or std::shared_ptr for automatic memory management, and ensure proper object ownership and lifecycle.
Finally, be rigorous in your check list. Ensure your test assertion ASSERT_EQ(int_values[1], 2); is referencing the right index and expecting the right value based on the actual behavior of your application.