Перевести код из С++ в С - C (СИ) (73706)
Формулировка задачи:
Друзья, я нуждаюсь в вашей помощи!
помогите перевести данный код из С++ в С
#include "stdafx.h" #include <stdio.h> #include <conio.h> #include <string.h> int main(int argc, char* argv[]) { static char str[256] = "c++ is object-oriented programming language. It was founded by Bjarne Straustrup many yours ago, and became a stadard for programming\0"; printf("string = %s\n\n", str); unsigned index = 0; char* pchars[] = { " ", "." }; while (index != sizeof(pchars) / sizeof(pchars[0])) { char **words = new char*[256], *temp = new char[256]; memset((void*)words, 0x00, 1024); strcpy(temp, str); unsigned max_len = 0, max_pos = 0; char* token = strtok(temp, pchars[index]); for (int n = 0; token != NULL; n++) { words[n] = new char[256]; strcpy(words[n], token); if (strlen(token) > max_len || max_len == 0) { max_len = strlen(token); max_pos = n; } token = strtok(NULL, pchars[index]); } printf("longest %s = %s len = %d\n", (index % 2) ? "phrase" : "word", words[max_pos], max_len); index++; } _getch(); return 0; }
Решение задачи: «Перевести код из С++ в С»
textual
Листинг программы
#include <stdio.h> #include <conio.h> #include <string.h> int main(int argc, char* argv[]) { static char str[256] = "c++ is object-oriented programming language. It was founded by Bjarne Straustrup many yours ago, and became a stadard for programming\0"; unsigned index = 0; char* pchars[] = { " ", "." }; printf("string = %s\n\n", str); while (index != sizeof(pchars) / sizeof(pchars[0])) { char **words = (char **)malloc(sizeof(char*)*256); char *temp = (char *)malloc(sizeof(char)*256); unsigned max_len = 0, max_pos = 0; char* token = 0; int n = 0; memset((void*)words, 0x00, 1024); strcpy(temp, str); token = strtok(temp, pchars[index]); for (n = 0; token != NULL; n++) { words[n] = malloc(sizeof(char)*256); strcpy(words[n], token); if (strlen(token) > max_len || max_len == 0) { max_len = strlen(token); max_pos = n; } token = strtok(NULL, pchars[index]); } printf("longest %s = %s len = %d\n", (index % 2) ? "phrase" : "word", words[max_pos], max_len); index++; } _getch(); return 0; }
Объяснение кода листинга программы
- Объявлена статическая строка
str
типаchar
с префиксным заполнителем нулевым символом и длиной 256 символов, содержащая строкуc++ is object-oriented programming language. It was founded by Bjarne Straustrup many yours ago, and became a stadard for programming
. - Объявлен массив
pchars
типаchar*
с двумя элементами:` (пробел) и
.` (точка). - Выводится содержимое строки
str
. - В цикле
while
происходит выделение памяти под массив указателей на строкиwords
и подстрокуtemp
длиной 256 символов. - В каждой итерации цикла происходит поиск максимальной длины подстроки в текущей части строки
str
, разделенной пробелом или точкой, и сохранение этой подстроки и её длины в соответствующем элементе массиваwords
. - После каждой итерации цикла выводится на экран самая длинная подстрока и её длина.
- После завершения цикла происходит смена индекса в массиве
pchars
. - В конце программы вызывается функция
_getch()
, предназначенная для приостановки выполнения программы до нажатия клавиши. - Программа возвращает 0, что означает успешный конец работы.
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д