I have until now:
int main(int argc, char * argv[]) {
std::vector<std::string> args;
for (int i = 1; i < argc; i ) {
args.push_back({ argv[i] });
}
std::string dateString = args[1];
return 0;
}
and I get Segmentation Fault on line: std::string dateString = args[1];
What I want to do is to use something like: ./myalgorithm.cpp 2022-09-01 where 2022-09-01 is a date. Then, I want to get to this date via argv[1], save it to a std::string variable and then do some computation with each value from the date( 2022, 09 and 01).
I was thinking to save this date to a string and then with the use of string.substr(...) to save into int variables the numbers from the date:
int year = stoi(mystring.substr(0,4));
int month = stoi(mystring.substr(6,2));
int day = stoi(mystring.substr(9,2));
EDIT: I edited my code and it works:
int main(int argc, char * argv[]) {
std::vector<std::string> args;
for (int i = 1; i < argc; i ) {
args.push_back({ argv[i] });
}
for (auto dateString: args) {
double year = stoi(dateString.substr(0,4));
double month = stoi(dateString.substr(5,2));
double day = stoi(dateString.substr(8,2));
std::cout << year << std::endl;
std::cout << month << std::endl;
std::cout << day << std::endl;
}
return 0;
}
But I don't understand why do I need to write:
std::vector<std::string> args;
for (int i = 1; i < argc; i ) {
args.push_back({ argv[i] });
}
Instead of simply:
std::vector<std::string> args;
args.push_back({ argv[1] });
EDIT:
Corrected Code:
int main(int argc, char * argv[]) {
std::vector<std::string> args;
if (argc > 1){
args.push_back({ argv[1] });
}
for (auto dateString: args) {
int year = stoi(dateString.substr(0,4));
int month = stoi(dateString.substr(5,2));
int day = stoi(dateString.substr(8,2));
int gpsweek = GPSweek(year, month, day);
printf("%d\n", gpsweek);
}
return 0;
}
CodePudding user response:
When you use ./myalgorithm.cpp 2022-09-01, what are argc and argv?
argc is count of arguments program name.
argv is program name and these arguments.
So argc = 2 and argv = { myalgorithm.cpp, 2022-09-01 }
std::vector<std::string> args;
for (int i = 1; i < argc; i ) {
args.push_back({ argv[i] });
}
After the code, the variable args is { "2022-09-01" } because you start from i = 1 but not 0.
C array (including std::vector) index starts from 0, so the first item has index being 0. If you try to take the second item with index = 1 then it is the array out of bounds. It is Undefined Behavior in C and Segmentation Fault is one of the outcomes.
Use args[0] to take the first item - "2022-09-01".
The range based for uses iterators which start from index = 0 for std::vector, therefore your correct code works.
