Перевести код из С++ в С - 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;
}

Объяснение кода листинга программы

  1. Объявлена статическая строка str типа char с префиксным заполнителем нулевым символом и длиной 256 символов, содержащая строку c++ is object-oriented programming language. It was founded by Bjarne Straustrup many yours ago, and became a stadard for programming.
  2. Объявлен массив pchars типа char* с двумя элементами: ` (пробел) и.` (точка).
  3. Выводится содержимое строки str.
  4. В цикле while происходит выделение памяти под массив указателей на строки words и подстроку temp длиной 256 символов.
  5. В каждой итерации цикла происходит поиск максимальной длины подстроки в текущей части строки str, разделенной пробелом или точкой, и сохранение этой подстроки и её длины в соответствующем элементе массива words.
  6. После каждой итерации цикла выводится на экран самая длинная подстрока и её длина.
  7. После завершения цикла происходит смена индекса в массиве pchars.
  8. В конце программы вызывается функция _getch(), предназначенная для приостановки выполнения программы до нажатия клавиши.
  9. Программа возвращает 0, что означает успешный конец работы.

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

11   голосов , оценка 4.182 из 5