Вот код языка Си, который я не могу доделать. typedef char* pochar; #include <windows.h>…
- User
Вот код языка Си, который я не могу доделать.
typedef char* pochar; #include <windows.h>
struct st_config { int config;//config[i]==<0 is char, >0 is int, count (e.g. -|5| is 5 is length) int mode;//mode=0=="001", or "aab"; mode=1=="1", or "b" int countfrom;//for example, from 001 to 100 or from 00140 to 01233 int countto; int conf_out(pochar chout) { chout=new pochar[countto-countfrom]; if(config<0)//char { config=config(-1); if(mode==1)//simple { char temp[config];//strlen using int tlen=0;//for strlen for (int i=0; i<countto-countfrom; i++) { chout[i]=new char[config];
wsprintf(chout[i], "%s", i); } } else { char temp[config];//strlen using int tlen=0;//for strlen for (int i=0; i<countto-countfrom; i++) { chout[i]=new char[config]; for(int t=0; t<i; t++) { } tlen=strlen(temp);//tlen=3 (3, 0, 0), so three numbers tlen=config-tlen;//for example config=7, 7-3=4, four spaces for(int t=tlen; t<=config; t++) temp[i]='0';//zero printing wsprintf(chout[i], "%s%d", temp, i); } } } else//number { if(mode==1)//simple { int num[config]={0,}; for (int i=0; i<countto-countfrom; i++) { chout[i]=new char[config]; wsprintf(chout[i], "%d", i); } } else { char temp[config];//strlen using int tlen=0;//for strlen for (int i=0; i<countto-countfrom; i++) { chout[i]=new char[config]; wsprintf(temp, "%d", i);//for example, 300 tlen=strlen(temp);//tlen=3 (3, 0, 0), so three numbers tlen=config-tlen;//for example config=7, 7-3=4, four spaces for(int t=tlen; t<=config; t++) temp[i]='0';//zero printing wsprintf(chout[i], "%s%d", temp, i); } } } return 0; }};
- Assistant
Что именно нужно доделать в этом коде?
- User
Это структура, в которой задают параметры:
st_config conf1; conf1.config=10;//если значение config>0, то будет генерировать числа, а меньше то символы. Длина по модулю определяет длину возвращаемой строки каждого элемента списка conf1.mode=0;//если значение mode=0, то "нам надо делать пропуски, то мы по началу записываем данные во временный буфер, мерим длину (например 3), отнимаем длину от длины всего буфера (получаем пропуски), сначала печатаем пропуски, а затем временный буфер" conf1.countfrom=101;//начинаем из 101 conf1.countto=1000;//заканчиваем на 1000
pochar *result=new pochar[conf1.countto-conf1.countfrom]; conf1.get(result);
Должно генерировать массив строк result, содержащих
Я уже запутался что содержащих
- Assistant
Вашей проблемой является to документирование и объяснение кода, а не его исправление.
Объясню вам основную логику кода:
- Структура
st_configопределяет параметры генерации последовательности чисел или символов. - Метод
conf_outгенерирует последовательность и сохраняет ее в переменнуюchout.
В коде есть несколько проблем:
- В строке
chout=new pochar[countto-countfrom];нет необходимости использоватьnew. Достаточно просто объявить массивpocharнужного размера. - В строке
wsprintf(chout[i], "%s", i);неправильно форматируется числоiв строку. Нужно использовать%dвместо%s. - В цикле
for(int t=0; t<i; t++)нет действий внутри цикла. Возможно, вам здесь нужно что-то добавить. - В строке
for(int t=tlen; t<=config; t++) temp[i]='0';ошибка. Нужноtemp[t], а неtemp[i]. - В строке
wsprintf(chout[i], "%s%d", temp, i);для форматирования числаiв строку нужно использовать%d, а не%s.
- Структура
- User
Напишите мне код, который генерирует последовательность символов или чисел, используя параметры структуры. Ну перепишите мой код вообще своим
- Assistant
Конечно! Ниже приведен исправленный код, который генерирует последовательность символов или чисел в соответствии с заданными параметрами:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef char* pochar; struct st_config { int config; int mode; int countfrom; int countto; void conf_out(pochar *chout) { int total = countto - countfrom; chout = (pochar*)malloc(total * sizeof(pochar)); if (config < 0) { // символы config = abs(config); for (int i = 0; i < total; i++) { chout[i] = (pochar)malloc((config + 1) * sizeof(char)); if (mode == 1) { // простой режим sprintf(chout[i], "%d", countfrom + i); } else { // режим с пропусками int num_zeros = config - strlen(chout[i]); sprintf(chout[i], "%0*d", num_zeros, countfrom + i); } } } else { // числа for (int i = 0; i < total; i++) { chout[i] = (pochar)malloc((config + 1) * sizeof(char)); sprintf(chout[i], "%d", countfrom + i); } } } }; int main() { st_config conf; conf.config = 10; conf.mode = 0; conf.countfrom = 101; conf.countto = 1000; pochar* result = NULL; conf.conf_out(result); // Выводим результат int total = conf.countto - conf.countfrom; for (int i = 0; i < total; i++) { printf("%s\n", result[i]); free(result[i]); } free(result); return 0; }