Задача №38 Изготвил: Мария Славова Ръководител: доц. Росен Радонов Фак.№941222033 гл ас д-р Мария Спасова



страница2/3
Дата18.03.2024
Размер152.72 Kb.
#120683
ТипЗадача
1   2   3
Документация на курсова работа
Свързани:
Заглавна-страница курсова работа 1
#include
#include
#include


int count_operators(char* line) {
int count = 0;
int len = strlen(line);
for (int i = 0; i < len; i++) {
if (line[i] == ';') {
count++;
}
}
return count;
}


int count_if_else(char* line) {
int count = 0;
int len = strlen(line);
for (int i = 0; i < len; i++) {
if (line[i] == 'i' && line[i+1] == 'f' && line[i+2] == '(') {
count++;
while (line[i] != ')') {
i++;
}
if (line[i+1] == '{') {
count++;
}
}
else if (line[i] == 'e' && line[i+1] == 'l' && line[i+2] == 's' && line[i+3] == 'e') {
count++;
if (line[i+4] == '{') {
count++;
}
}
}
return count;
}


void read_and_write() {
char program_filename[50];
char result_filename[50];
printf("Enter the name of the program file (.c): ");
scanf("%s", program_filename);
printf("Enter the name of the result file: ");
scanf("%s", result_filename);


FILE* program_fp = fopen(program_filename, "r");
if (program_fp == NULL) {
printf("Error opening program file\n");
return;
}


FILE* result_fp = fopen(result_filename, "w");
if (result_fp == NULL) {
printf("Error opening result file\n");
fclose(program_fp);
return;
}


int operator_count = 0;
int if_else_count = 0;
char line[100];
while (fgets(line, 100, program_fp) != NULL) {
operator_count += count_operators(line);
if_else_count += count_if_else(line);
}


fprintf(result_fp, "Number of operators: %d\n", operator_count);
fprintf(result_fp, "Number of if and if-else statements: %d\n", if_else_count);


printf("Result written to file %s\n", result_filename);


fclose(program_fp);
fclose(result_fp);
}


void read_and_print() {
char filename[50];
printf("Enter the name of the program file (.c): ");
scanf("%s", filename);


FILE* fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error opening program file\n");
return;
}


int operator_count = 0;
int if_else_count = 0;
char line[100];
while (fgets(line, 100, fp) != NULL) {
operator_count += count_operators(line);
if_else_count += count_if_else(line);
}


printf("Number of operators: %d\n", operator_count);
printf("Number of if and if-else statements: %d\n", if_else_count);


fclose(fp);
}


int main() {
int choice;
do {
printf("\nMenu:\n");
printf("1. Read program from file and write result to file\n");
printf("2. Read program from file and print result to screen\n");
printf("3. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);


switch (choice) {
case 1:
read_and_write();
break;
case 2:
read_and_print();
break;


Сподели с приятели:
1   2   3




©obuch.info 2024
отнасят до администрацията

    Начална страница