start lab 2

This commit is contained in:
Trygve 2024-02-26 13:11:04 +01:00
parent 3bd57bd8f2
commit 03b9bb9ab2

41
lab_2/8_wildptr-fixed.cpp Normal file
View File

@ -0,0 +1,41 @@
#include <cassert>
#include <cstring>
#include <iostream>
void crop(int num_strings, char** strings, int characters_cropped);
int main(int argc, char** argv)
{
/* crop the first two letters of each input argument,
* by jumping from index 0 to index 2
*/
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.
*/
void crop(int num_strings, char** strings, 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
*/