IZP/Cviko3_2/main.c
2024-10-03 17:17:16 +02:00

114 lines
2.5 KiB
C

#include "types.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* Safely print first argument provided to the program. Determine its meaning.
*
* @param argc total number of arguments provided to the program
*
* @param argv array/vector of arguments
*/
void print_first_argument(int argc, char *argv[]) {
if (argc < 1) {
return;
}
printf("%s\n", argv[0]);
return;
}
/**
* Safely print first 4 arguments provided to the program while converting them
* to their corresponding data type.
*
* ./main <int> <double> <string>
*
* To convert <string> to <int>, use function atoi()
* (https://cplusplus.com/reference/cstdlib/atoi/)
*
* To convert <string> to <double>, use function atof()
* (https://cplusplus.com/reference/cstdlib/atof/)
*
* Use the following commmand to execute your program with set of arguments:
*
* ./main 42 13.37 hello_program
*
* @param argc total number of arguments provided to the program
*
* @param argv array/vector of arguments
*/
void print_parse_arguments(int argc, char *argv[]) {
int a;
double b;
int s = (argc<4)?argc:4;
for (int i = 0; i < s; ++i) {
switch (i) {
case 1:
a = atoi(argv[i]);
printf("%d\n",a);
break;
case 2:
b = atof(argv[i]);
printf("%.3f\n",b);
break;
default:
printf("%s\n",argv[i]);
break;
}
}
return;
}
/**
* Safely print ALL arguments provided to the program without any conversion.
*
* ./main <int> <double> <string>
*
* @param argc total number of arguments provided to the program
*
* @param argv array/vector of arguments
*/
void print_all_arguments(int argc, char *argv[]) {
for (int i = 0; i < argc; ++i) {
printf("%s\n", argv[i]);
}
return;
}
/**
* Safely print the largest argument
*
* ./main <int> <double> <string>
*
* @param argc total number of arguments provided to the program
*
* @param argv array/vector of arguments
*/
void print_largest_argument(int argc, char *argv[]) {
char *c = "";
for (int i = 0; i < argc; ++i) {
if(strlen(argv[i]) > strlen(c)){
c = argv[i];
}
}
printf("Largest argument: %s",c);
return;
}
#ifndef TEST_BUILD
int main(int argc, char *argv[]) {
printf("\n-- print_first_argument --\n");
print_first_argument(argc, argv);
printf("\n-- print_parse_arguments --\n");
print_parse_arguments(argc, argv);
printf("\n-- print_all_arguments --\n");
print_all_arguments(argc, argv);
printf("\n-- print_largest_argument --\n");
print_largest_argument(argc, argv);
return 0;
}
#endif