INF205/lab_2/8_wildptr-fixed.cpp
2024-02-26 13:16:42 +01:00

42 lines
1.2 KiB
C++

#include <cassert>
#include <cstring>
#include <iostream>
constexpr void crop(int num_strings, char** strings, int characters_cropped);
int main(const int argc, char** argv)
{
/* crop the first two letters of each input argument,
* by jumping from index 0 to index 2
*/
const int jump_to_index = 2;
/* crop all of the strings in argv, except the one with index 0;
* note that argv[0] is always the program's name.
* only the argv[i] with i > 0 are genuine command-line arguments.
*/
crop(argc-1, argv+1, jump_to_index);
for(int i = 1; i < argc; i++)
std::cout << "Argument no. " << i
<< " was cropped to \"" << argv[i] << "\".\n";
}
/* implementation that "crops" a string by incrementing it, so that
* it effectively begins <characters_cropped> characters further ahead.
*/
constexpr void crop(int num_strings, char** strings, const int characters_cropped)
{
assert(characters_cropped >= 0);
for(int i = 0; i < num_strings; i++)
if(strlen(strings[i]) >= characters_cropped)
strings[i] += characters_cropped;
else strings[i] += strlen(strings[i]);
}
/* make and try executing:
* ./wildptr-fixed ABCDE FGHIJ KLMNO
* ./wildptr-fixed ABCDE FGHI JKL MN O
*/