@@ -402,6 +402,35 @@ def final_trim(self, instruction_name:str, line_number:int):
402402 ):
403403 self .instructions_list [line_number ] = self .instructions_list [line_number ].replace (algo_function , cpp_function )
404404
405+ # Function to find all the instances of a substring in a string
406+ def find_all (full_string : str , search : str ):
407+ """
408+ Finds all instances of a substring in a string.
409+ :param full_string: The string to search into.
410+ :param search: The string of whom to find all the instances.
411+ :return: A generator containing all the indexes of the substring.
412+ """
413+ start = 0
414+ while True :
415+ start = full_string .find (search , start )
416+ if start == - 1 : return
417+ yield start
418+ start += len (search )
419+
420+ # Adds the len function
421+ if "len(" in self .instructions_list [line_number ]:
422+ for index in find_all (self .instructions_list [line_number ], "len(" ):
423+ var_name = self .instructions_list [line_number ][
424+ index + 4 :
425+ index + 4 + self .instructions_list [line_number ][index + 4 :].find (")" )
426+ ]
427+ self .instructions_list [line_number ] = self .instructions_list [line_number ].replace (
428+ f"len({ var_name } )" ,
429+ f"(sizeof({ var_name } )/sizeof({ var_name } [0]))" ,
430+ 1
431+ )
432+
433+
405434 # Adds the correct tabbing (amount of tabs is equal to amount of instructions in the instructions stack,
406435 # minus one if the current instruction is in the instruction names)
407436 tab_amount = len (self .instructions_stack )
@@ -447,6 +476,10 @@ def final_touches(self):
447476 if 'aleatoire(' in self .app .current_text or 'alea(' in self .app .current_text :
448477 final_compiled_code += "#include <stdlib.h>\n #include <time.h>\n "
449478
479+ # If we use len in the code, we import stdlib.h
480+ if 'len(' in self .app .current_text :
481+ final_compiled_code += "#include <stdlib.h>\n "
482+
450483 # If we use the std namespace, we put it there
451484 if self .app .using_namespace_std :
452485 final_compiled_code += "using namespace std;\n "
0 commit comments