prog_avancee_C/TP3/decoupage.c

84 lines
2.0 KiB
C
Raw Normal View History

2024-10-22 13:03:17 +02:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int * int_list_from_str(char * str);
int int_count_from_str(char * str);
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <string>\n", argv[0]);
return -1;
}
printf("%d ints\n", int_count_from_str(argv[1]));
/*int * list = int_list_from_str(argv[1]);
for (int i=0; i<int_count_from_str(argv[1]); i++) {
printf("%d ", list[i]);
}*/
return 0;
}
int * int_list_from_str(char * str) {
int ico = int_count_from_str(str);
int * list = malloc(sizeof(int)*ico);
int len = strlen(str);
int current_i = 0;
int is_i = 1;
int ic = 0;
for (int i = 0; i < len; i++) {
if (str[i] == ' ') {
if ((i+1 < len && str[i+1] != ' ') || (i+1)==len) {
list[ic] = current_i;
ic++;
}
is_i = 0;
current_i = 0;
} else if (isdigit(str[i])) {
if (is_i) {
current_i *= 10;
} else {
is_i = 1;
}
current_i += (str[i] - '0');
} else if (str[i]=='-' && current_i > 0) {
current_i *= -1;
} else {
return 0;
}
}
return list;
}
int int_count_from_str(char * str) {
int ic = 0;
int current_i = 0;
int is_i = 1;
int len = strlen(str);
for (int i = 0; i < len; i++) {
printf("str[%d]: %c\n", i, str[i]);
if (str[i] == ' ') {
if ((i+1 < len && str[i+1] != ' ') || (i+1)==len) ic++;
is_i = 0;
current_i = 0;
} else if (isdigit(str[i])) {
if (is_i) {
current_i *= 10;
} else {
is_i = 1;
}
current_i += (str[i] - '0');
} else if (str[i]=='-' && current_i > 0) {
current_i *= -1;
} else {
return 0;
}
}
return ic;
}