Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Центр помощи > [C++] Задача


Автор: redrover 31.1.2010, 12:42
Требуется решить задачу... Он а, в принципе, не сложная, просто я всегда испытываю трудности при работе с файлами...
Помогите, пожалуйста. smile 

Вот сама задача: 
Дан текстовый файл F. Найти предложение с максимальным количеством чисел
(целых или действительных). Если таких предложений несколько, найти их все.
Переписать эти предложения в другой файл G.



Автор: mrbrooks 1.2.2010, 09:58
redrover, какая структура исходного файла?

Автор: redrover 2.2.2010, 23:10
mrbrooks, представьте себе абзац учебника истории.) 
Просто текст, который содержит числа...
Оцените мое собственное, весьма кривое решение этой задачи.  smile 
Код

// Задача_№2.cpp
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <conio.h>
using namespace std;

char str[100][1024];
int key[100];

int metod_max ()
{
    int max = key[0]; 
    int ind = 0;
    for ( int i = 1; i < 100; i++ ) 
    {
        if ( max < key[i] ) 
        {
            max = key[i];
            ind = i;
        }
    }
    cout << "GG: " << ind;
    return ind;
}

void rezac ( char* text, int n )
{
    int k = 0; int i = 0;
    for ( int l = 0; l < n; l++ )
    {
        str[k][i++] = text[l];
        if (text[l] == '.') 
        {
            k++;
            i = 0;
        }
    }
}

void metod_chisl ( int num )
{
    for ( int g = 0; g < num; g++ )
    {
        int i = 0;
        int k = 0;
        while ( str[g][i] != '.'  )
        {
            if ( ( str[g][i] == '1' || str[g][i] == '2' || str[g][i] == '3' || str[g][i] == '4' || str[g][i] == '5' || str[g][i] == '6' || str[g][i] == '7' || str[g][i] == '8' || str[g][i] == '9' ||str[g][i] == '0' ) 
                && ( str[g][i+1] != '0' && str[g][i+1] != '1' && str[g][i+1] != '2' && str[g][i+1] != '3' && str[g][i+1] != '4' && str[g][i+1] != '5' && str[g][i+1] != '6' && str[g][i+1] != '7' && str[g][i+1] != '8' && str[g][i+1] != '9' ) )
            {
                k++; 
            }
            i++;
        }
        /*if ( k < 15)*/ key[g] = k;
        /*cout << k << ' ';*/ // g -- num
    }
}

int main()
{
    char *text = new char[10240];
    for ( int i = 0; i < 10240; i++ )
        text[i] = ' ';
    for (int i = 0; i < 100; i++) key[i] = 0;

    FILE* fn;
    fn = fopen("D:\\F.txt", "rt");
    fgets( text, 10240 , fn ); 
    fclose(fn);

    int kolv = strlen(text);
    int predl = 0;
    for ( int i = 0; i < 10240; i++ )
        if ( text[i] == '.' ) predl++;
    puts(text);

    cout << endl;

    rezac(text, kolv);
    metod_chisl( predl );

    cout << "hash: \n";
    for ( int i = 0; i < predl; i++ ) cout << key[i] << ' ';

    cout << endl;

    int get = metod_max();

    fn = fopen("D:\\G.txt", "at");
    for ( int i = 0; i < predl; i++ )
    {
        if ( key[i] == key[get] && i != get ) fputs( str[i], fn );
    }
    fputs( str[get], fn );
    fclose(fn);

    _getche();
    return 0;
}



Автор: mrbrooks 3.2.2010, 11:51
redrover, злобно. 
Вот входящий файл:
Цитата

1234454 trololo 123451 trololo 6542 trololo 5254 trololo 1244 trololo 45744 458 trololo 78945. trololo 784 trololo 1235 trololo 22 trololo 334584. trololo 888 trololo 999977 trololo 235 trololo 77 trololo 333 trololo 44454. trololo 89745 trololo 78454 trololo 22 v 584. 333 trololo 2 trololo 4454 trololo. 1234454 trololo 123451 trololo 6542 trololo 5254 trololo 1244 trololo 45744 458 trololo 78945.


то:
Код


#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>

int main()
{
    typedef std::multimap<int,std::string>::iterator ItMap;
    std::fstream file("F",std::fstream::in);
    if (file)
    {
        std::string text = "";
        std::vector<std::string>vector;
        //на тот случай если несколько строк
        //с максимальным количеством чисел
        std::multimap<int,std::string>dic;  
        int max_counter = 0;
        while (!file.eof())
        {
            getline(file,text,'.');
            boost::algorithm::split_regex(vector,text,boost::regex(" "));
            int counter = 0;
            BOOST_FOREACH(std::string s,vector)
            {            
                try
                {
                    boost::lexical_cast<int>(s);
                    counter++;
                }
                catch (boost::bad_lexical_cast &){}
            }            
            dic.insert(std::pair<int,std::string>(counter,text));
            if (max_counter < counter) max_counter = counter;
        }
        file.clear();
        file.close();

        file.open("G",std::fstream::out);
        if(file)
        {
            ItMap it = dic.begin();
            std::pair<ItMap, ItMap>ret;
            ret = dic.equal_range(max_counter);
            for (it=ret.first;it!=ret.second;++it)
                file << (*it).second << std::endl;
            file.close();
        }
    }
    return 0;
}


Автор: redrover 3.2.2010, 20:04
Красивое решение, спасибо. 
Прикреплю к материалам дела.))

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)