Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 26.02.2018, 20:02   #1
alexboliam
Пользователь
 
Регистрация: 10.10.2017
Сообщений: 44
По умолчанию Ошибка в коде, я все закомментил(для удобства)

Здравствуйте, задание таково: создать текстовый файл, в каждой четной строке найти самое длинное слово и потом все эти самые длинные слова дописать в нечетные строки. Сделал я это всё, как в коде ниже, только проблема вот в чём: когда пользователь вводит четное количество строк, программа всё делает отлично, но когда ввести, к примеру, 3 строки - выдает некрасивую картину из символов после нечетных строк. Если ввести 5 строк, вообще срабатывает точка останова. Помогите, пожалуйста, код весь закомментил.
P.S. P.S. Ошибка скорее всего где-то в функции addToOddStrings или в case 2 в меню.
Код:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
using namespace std;
 
int input(char**);//input string
void printFile();//print file to console
bool writeToFile(char**, int);//write strings to file
char* maxLenWord(char*);//create massive of longest words
bool addToOddStrings(char*);//append odd strings with longest words
 
int main() {
    char**lines = new char *[255];//create ptr for strings array
    for (int i = 0; i < 255; i++) {
        lines[i] = new char[255];
    }
    int a;// var for menu
    bool flag = true; int linecount;//var for menu and number of lines
    linecount = input(lines);//input strings and count number of lines
    writeToFile(lines, linecount);//write this lines to txt file
    system("cls");//clear console
    while (flag) {//menu cycle
        cout << "\t Menu \n 1. Show the content of file\n 2. Change odd strings\n 3. Exit\n";
        cout << "Enter the number: ";
        cin >> a;//enter menu item
        switch (a) {//menu mechanism
        case 1://if user choose 1st item
        {
            system("cls");
            printFile();//print text to console
            cout << "\n Press any button to continue";
            _getch();//take any key
            system("cls");
            break;
        }
        case 2:
        {
            system("cls");
            if (linecount < 3) {//if user wrote 0 or 1 string
                cout << "Please, Restart program and enter 2 or more strings\nPress any key to continue" << endl;
                _getch();
                system("cls");
                break;
            }
            int count;//var for number of even strings
            if (linecount % 2 != 0) {//find number of strings to find longest words from
                count = (linecount / 2) + 1;//if number of lines is odd
            }
            else {
                count = linecount / 2;//if number of lies is even
            }
            char**words = new char*[count];//array for longest words
            for (int i = 0, j = 1; i < count; i++, j += 2) {// take longest words from every even line 
                words[i] = maxLenWord(lines[j]);//and write it to array
            }
            char *allwords = new char[255];// array with all longest words
            strcpy(allwords, "");
            for (int i = 0; i < count; i++) {//write all longest words to this array
                strcat(allwords, " ");//put spaces between words
                strcat(allwords, words[i]);//put words
            }
            addToOddStrings(allwords);//write all longest words to odd strings
            printFile();//print text to console
        }
        case 3:// exit case
        {
            flag = false;//flag to exit from cycle
            break;
        }
        default://case of taking wrong number for menu
        {
            cout << "Error"; 
            _getch(); 
            system("cls"); 
            break;
        }
        }
    }
    system("pause");
    return 0;
}
 
int input(char**lines) {
    char *str = new char[255];//buff array
    int i = 0;//counter of lines array
    char a;//char to continue or break
    bool flag;//flag to continue cycle
    do {
        system("cls");//clear console
        cout << "Enter string for the file:\n ";
        cin.getline(str, 255);//take user`s string to buffer
        strcpy(lines[i++], str);//copy string to array
        cout << "Press Y to continue or any button to stop";//continue request
        a = _getch();
        cout << endl;
        if (a == 'y' || a == 'Y') {//continue 
            flag = true;
        }
        else {//stop
            flag = false;
        }
    } 
    while (flag);
    return i;//return number of lines
}
bool writeToFile(char**lines, int linecount) {
    FILE *file = fopen("lab.txt", "w");//open file for write
    if (file == NULL)
        return false;
    char *buff = new char[255*2];//buff array
    for (int i = 0; i < linecount; i++) {
        strcpy(buff, lines[i]);//copy string from array to buffer
        strcat(buff, "\n");
        fputs(buff, file);//put string to file
    }
    fclose(file);//close file
    return true;
}
void printFile() {
    string temp;//buff string
    ifstream file("lab.txt");//open file 
    if (file) {//if file is opened
        while (getline(file, temp)) {//take every line from file to buff
            cout << temp << endl;//print line from buff to console
        }
    }
}
char* maxLenWord(char *lines) {
    char* buf = new char[255*255];//buffer array
    strcpy(buf, lines);//copy from line array to buff
    const char* delim = " ,.";//delimiters
    char* np = NULL;//ptr to next lexeme
    char* p = strtok(buf, delim);//create ptr to current lexeme
    int maxlen = strlen(p);//max length, take length of current word for start
    char* maxword = p;//string with max length word
    while (p != NULL)//while there are lexemes
    {
        p = strtok(NULL, delim);
        if (p == NULL)//if there are no lexems - stop
            break;
        if (maxlen < strlen(p))//if maxlen is less than len of current lexeme
        {
            maxword = p;//change maxword to current lexeme
            maxlen = strlen(p);//change maxlen to len of current lexeme
        }
    }
    return maxword;//return max length word
}
bool addToOddStrings(char* st) {
    FILE* file = fopen("lab.txt", "r");//open file to read
    if (file == NULL) {//if file is not found - stop
        return false;
    }
    char**lines = new char*[255];//create buff text array
    for (int i = 0; i < 255; i++) {
        lines[i] = new char[255];
    }
    int linecount = 0;//number of lines
    int i = 0;//lines array counter
    while (!feof(file)) {//while there is not end of file
        fgets(lines[i], 255, file);//get line from file to buff strings array
        i++;//next buff line
        linecount++;//increase number of lines
    }
    linecount--;//decrease by 1 because of start from 0
    fclose(file);//close file
 
    file = fopen("lab.txt", "w");//file open for writing
    char *tmpStr = new char[255];// line buff
    int tmp;
    for (int i = 0; i < linecount; i++) {
        if (i % 2 == 0) {//if line is odd(because entered lines count starts from 1, not from 0)
            strcpy(tmpStr, "");
            strcpy(tmpStr, lines[i]);//copy string from text buff to line buff
            memset(tmpStr + (strlen(lines[i]) - 1) * sizeof(char), 0, 1);
            strcat(tmpStr, " ");//put space between line and array of maxlen words
            strcat(tmpStr, st);//put maxlen words
            strcat(tmpStr, "\n");//put enter symbol
            fputs(tmpStr, file);//put finale line to file
        }
        else {//for even lines do the same without putting maxlen words
            strcpy(tmpStr, "");
            strcpy(tmpStr, lines[i]);
            strcat(tmpStr, "\n");
            fputs(tmpStr, file);
        }   
    }
    fclose(file);//close file
    return true;
}

Последний раз редактировалось alexboliam; 26.02.2018 в 20:08.
alexboliam вне форума Ответить с цитированием
Старый 26.02.2018, 20:14   #2
p51x
Старожил
 
Регистрация: 15.02.2010
Сообщений: 15,707
По умолчанию

1. У вас куча выделений памяти. Где хоть одно удаление?
2.
Код:
                count = (linecount / 2) + 1;//if number of lines is odd

            for (int i = 0, j = 1; i < count; i++, j += 2) {// take longest words from every even line 
                words[i] = maxLenWord(lines[j]);//and write it to array
            }
Берем linecount = 3 ->count = 2. Какие значение примет j? Вы точно уверены, что в лайнес заполнены строки по данным индексам? И да память незануляется автоматически (кроме оговоренных случаев).
p51x вне форума Ответить с цитированием
Старый 26.02.2018, 20:27   #3
alexboliam
Пользователь
 
Регистрация: 10.10.2017
Сообщений: 44
По умолчанию

Спасибо!!!Увидел, что проблема в этом фрагменте и уже исправил. Очищение памяти сейчас займусь
alexboliam вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Фермеру Ивану выделено N квадратных единиц посевной площади. Для удобства artem16rus Фриланс 3 19.05.2017 16:10
Плюшка для удобства. min@y™ Windows 14 24.09.2015 11:11
Ошибка в коде. Из числового множества A мощности n выбрать все подмножества FYNZIK Помощь студентам 0 25.05.2014 22:19
Ошибка в коде.С числовой множества A мощности n выбрать все подмножества FYNZIK Общие вопросы C/C++ 0 24.05.2014 14:39
Ошибка в коде программы (для индекса требуется массив или указатель). Язык Си Семижон Евгения Помощь студентам 7 20.01.2014 02:45