Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.91/11: Рейтинг темы: голосов - 11, средняя оценка - 4.91
0 / 0 / 0
Регистрация: 16.03.2011
Сообщений: 44
1

Считать текст из файла, и вывести только предложения, в которых нет запятой

19.09.2011, 13:30. Показов 1910. Ответов 17
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Написать програму которая считывает текст из файла и выводит на екран только предложения в которых нету запятой?
Это надо сделать через роботу с файлами.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
19.09.2011, 13:30
Ответы с готовыми решениями:

Считать текст из файла. Вывести на экран только восклицательные предложения
Считать текст из файла. Вывести на экран только восклицательные предложения.

Считать текст из файла и вывести на экран только восклицательные предложения
C++ Разработать программу, которая считывает текст из файла и выводит на экран только...

Считать текст из файла и вывести на экран только предложения не содержащие запятых
написать программу которая считывает текст из файла и выводит на экран только предложения не...

Считать текст из файла и вывести на экран монитора только определенные предложения
Считать текст из файла и вывести его на экран монитора только предложения, содержащие информацию о...

17
794 / 546 / 61
Регистрация: 11.05.2010
Сообщений: 1,298
Записей в блоге: 1
19.09.2011, 13:44 2
Цитата Сообщение от pashokman Посмотреть сообщение
Написать програму которая считывает текст из файла
Цитата Сообщение от pashokman Посмотреть сообщение
Это надо сделать через роботу с файлами.
pashokman, а есть варианты?

И вообще, у вас самого есть варианты?
0
0 / 0 / 0
Регистрация: 16.03.2011
Сообщений: 44
19.09.2011, 13:46  [ТС] 3
нету вариантов потому и спрашиваю если можете помогите плз с заданием
0
794 / 546 / 61
Регистрация: 11.05.2010
Сообщений: 1,298
Записей в блоге: 1
19.09.2011, 13:58 4
pashokman, читаете строку до первой точки или до конца файла, далее проходите по символам. Если встретится запятая - выходите из цикла и читайте следующее предложение. Если дошли до нуль-терминатора, то это значит, что запятая не встретилась, и можно выводить предложение. Реализация - за вами.
0
0 / 0 / 0
Регистрация: 16.03.2011
Сообщений: 44
19.09.2011, 14:27  [ТС] 5
вот с етим у меня и возникла проблема я словами могу описать решение а как кодом написать не знаю
0
794 / 546 / 61
Регистрация: 11.05.2010
Сообщений: 1,298
Записей в блоге: 1
19.09.2011, 14:31 6
pashokman, читайте литературу по С++, иначе ваша проблема никуда не уйдёт
0
программист С++
860 / 600 / 147
Регистрация: 19.12.2010
Сообщений: 2,014
19.09.2011, 15:12 7
на вход:
There are times when a generic (in the sense of general as opposed.
to template-based programming) type is needed: variables that are truly variable, accommodating.
values of many other more specific types rather than C++'s normal strict and static types.
We can distinguish three basic kinds of generic type.
Converting types that can hold one of a number of possible value types, e.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <fstream>
#include <list>
#include <string>
#include <algorithm>
#include <conio.h>
#include <cstdlib>
#include <iterator>
#include <xstddef>
 
struct not_contain :
    public std::binary_function<std::string, char, bool>
{
    bool operator()(const std::string& value, char key) const
    {
        return value.find(key, 1) != std::string::npos;
    }
};
 
int main()
{
    const std::string file_name("text.txt");
    const std::string file_name_out("text_o.txt");
 
    std::fstream file(file_name, std::ios_base::in);
    std::fstream file_o(file_name_out, std::ios_base::out);
    if (file.fail() || file_o.fail())
    {
        std::cerr << "Bad file or file name" << std::endl;
        _getch();
        return EXIT_FAILURE;
    }
 
    std::string text;
    std::copy(std::istreambuf_iterator<char>(file), 
        std::istreambuf_iterator<char>(), std::back_inserter(text));
 
    file_o << "Text: " << std::endl << text;
 
    std::list<std::string> sentences;
    std::string::iterator i = text.begin(), j = i;
    while (i != text.end())
    {
        i = std::find(j, text.end(), '.');
        if (i != text.end())
        {
            sentences.push_back(std::string(j, i));
            j = i.operator++();
        }
    }
 
    file_o << std::endl << "\tParse:" << std::endl;
    std::copy(sentences.begin(), sentences.end(), std::ostream_iterator<std::string>(file_o, "\n"));
 
    std::list<std::string>::const_iterator new_end = 
        std::remove_if(sentences.begin(),
        sentences.end(), std::bind2nd(not_contain(), ','));
 
    sentences.erase(new_end, sentences.end());
 
    file_o << std::endl << "\tAnswer: " << std::endl; 
    std::copy(sentences.begin(), sentences.end(), std::ostream_iterator<std::string>(file_o, "\n"));
 
    _getch();
    return EXIT_SUCCESS;
}
ответ:
Text:
There are times when a generic (in the sense of general as opposed.
to template-based programming) type is needed: variables that are truly variable, accommodating.
values of many other more specific types rather than C++'s normal strict and static types.
We can distinguish three basic kinds of generic type.
Converting types that can hold one of a number of possible value types, e.
Parse:
There are times when a generic (in the sense of general as opposed

to template-based programming) type is needed: variables that are truly variable, accommodating

values of many other more specific types rather than C++'s normal strict and static types

We can distinguish three basic kinds of generic type

Converting types that can hold one of a number of possible value types, e

Answer:
There are times when a generic (in the sense of general as opposed

values of many other more specific types rather than C++'s normal strict and static types

We can distinguish three basic kinds of generic type
1
0 / 0 / 0
Регистрация: 16.03.2011
Сообщений: 44
19.09.2011, 15:16  [ТС] 8
sandye51 спасибо за ришение но не могли бы вы написать это на С а не на С++?
0
В астрале
Эксперт С++
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
19.09.2011, 15:20 9
pashokman, Перепишите. В чем проблема-то?
0
Заблокирован
Автор FAQ
19.09.2011, 15:21 10
Цитата Сообщение от pashokman Посмотреть сообщение
Написать програму которая считывает текст из файла и выводит на екран только предложения в которых нету запятой?
Это надо сделать через роботу с файлами.
Вот на Си
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdlib.h> //malloc
#include <string.h> //strlen strtok
#include <stdio.h>  //i/o
 
int main()
{
    long sLen;
    char * str, *buf;
    char delim[] = ".!?";//Разделители предложений
    FILE * f = fopen("text.txt","rb+");
    if(!f)
        printf("Error open text.txt\r\n");
    else
    {
        fseek(f,0,SEEK_END);
        sLen = ftell(f);
        fseek(f,0,SEEK_SET);
        if(!(str = (char *)malloc(sLen + 1)))
            printf("allocation memory error\r\n");
        else
        {
            fread(str,sLen,1,f);
            str[sLen] = '\0';
        }
        fclose(f);
        if(str)
        {
            //Разбиваем текст на предложения
            buf = strtok(str,delim);
            while(buf)
            {
                //Выводим предложения если не найдена запятая
                if(!strchr(buf,','))
                    printf("%s.\r\n",buf);
                buf = strtok(NULL,delim);
            }
        }
    }
    printf("\r\nEnter any key\r\n");
    char ch;scanf("%c",&ch);
    return 0;
}
text.txt
Gravitational collapse is the inward fall of a body due to the influence of its own gravity. In any stable body, this gravitational force is counterbalanced by the internal pressure of the body, in the opposite direction to the force of gravity (gravity being generally orientated to the center of mass). If the inwards pointing gravitational force, however, is stronger than the total combination of the outward pointing forces, the equilibrium becomes unbalanced and a collapse occurs until the internal pressure increases above that of the gravitational force and a equilibrium is once again attained (the exception being black holes).
Because gravity is comparatively weak compared to other fundamental forces, gravitational collapse is usually associated with very massive bodies or collections of bodies, such as stars (including collapsed stars such as supernovae, neutron stars and black holes) and massive collections of stars such as globular clusters and galaxies.
Gravitational collapse is at the heart of structure formation in the universe. An initial smooth distribution of matter will eventually collapse and cause a hierarchy of structures, such as clusters of galaxies, stellar groups, stars and planets. For example, a star is born through the gradual gravitational collapse of a cloud of interstellar matter. The compression caused by the collapse raises the temperature until nuclear fuel reignites in the center of the star and the collapse comes to a halt. The thermal pressure gradient (leading to expansion) compensates the gravity (leading to compression) and a star is in dynamical equilibrium between these two forces.
Gravitational collapse of a star occurs at the end of its lifetime, also called the death of the star. When all stellar energy sources are exhausted, the star will undergo a gravitational collapse. In this sense a star is in a "temporary" equilibrium state between a gravitational collapse at stellar birth and a further gravitational collapse at stellar death. The end states are called compact stars.
The types of compact stars are:
White dwarfs, in which gravity is opposed by electron degeneracy pressure;
Neutron stars, in which gravity is opposed by neutron degeneracy pressure and short-range repulsive neutron-neutron interactions mediated by the strong force;
Black holes, in which the physics at the center is unknown.
The collapse to a white dwarf takes place over tens of thousands of years, while the star blows off its outer envelope to form a planetary nebula. If it has a companion star, a white dwarf-sized object can accrete matter from a companion star until it reaches the Chandrasekhar limit, at which point gravitational collapse takes over again. While it might seem that the white dwarf might collapse to the next stage (neutron star), they instead undergo runaway carbon fusion, blowing completely apart in a Type Ia supernova. Neutron stars are formed by gravitational collapse of larger stars, the remnant of other types of supernova.
Even more massive stars, above the Tolman-Oppenheimer-Volkoff limit cannot find a new dynamical equilibrium with any known force opposing gravity. Hence, the collapse continues with nothing to stop it. Once it collapses to within its Schwarzschild radius, not even light can escape from the star, and hence it becomes a black hole. According to theories, at some point later the collapsing object will reach the maximum possible energy density for a certain volume of space or the Planck density (as there is nothing that can stop it), where the known laws of gravity cease to be valid.[1] There are competing theories as to what occurs at this point, but it can no longer really be considered gravitational collapse at that stage.
It might be thought that a sufficiently large neutron star could exist inside its Schwarzschild radius and appear like a black hole without having all the mass compressed to a singularity at the center; however, this is a misconception. Within the event horizon, matter would have to move outwards faster than the speed of light in order to remain stable and avoid collapsing to the center. No physical force can therefore prevent the star from collapsing to a singularity (at least within the currently understood framework of general relativity). A model for nonspherical collapse in general relativity with emission of matter and gravitational waves was presented in [2].

Вывод консоли

Gravitational collapse is the inward fall of a body due to the influence of its
own gravity.

Gravitational collapse is at the heart of structure formation in the universe.
The compression caused by the collapse raises the temperature until nuclear fue
l reignites in the center of the star and the collapse comes to a halt.
The thermal pressure gradient (leading to expansion) compensates the gravity (l
eading to compression) and a star is in dynamical equilibrium between these two
forces.
In this sense a star is in a "temporary" equilibrium state between a gravitatio
nal collapse at stellar birth and a further gravitational collapse at stellar de
ath.
The end states are called compact stars.
No physical force can therefore prevent the star from collapsing to a singulari
ty (at least within the currently understood framework of general relativity).
A model for nonspherical collapse in general relativity with emission of matter
and gravitational waves was presented in [2].

Enter any key
1
0 / 0 / 0
Регистрация: 16.03.2011
Сообщений: 44
19.09.2011, 15:24  [ТС] 11
ВСЕМ БОЛЬШОЕ СПАСИБО!!!
0
794 / 546 / 61
Регистрация: 11.05.2010
Сообщений: 1,298
Записей в блоге: 1
19.09.2011, 15:29 12
pashokman, так вы никогда не станете программистом.

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
 
#define BUFF_SIZE 4096
 
int read_sentence( char * buff, size_t buff_size, FILE * fd )
{
    char ch;
    size_t buff_it = 0;
 
    while( !feof(fd) && buff_it < buff_size - 1 )
    {
        ch = fgetc(fd);
 
        buff[ buff_it ] = ch;
        buff_it++;
 
        if( ch == '.' )
           break;
    }
 
    buff[ buff_it ] = 0;
 
    return buff_it;
}
 
int main()
{
    FILE * in = fopen( "input.txt", "r" );
 
    char buff[ BUFF_SIZE ];
    int i;
 
    while( !feof(in) )
    {
        int read = read_sentence( buff, BUFF_SIZE, in );
 
        char comma_found = 0;
 
        for( i = 0; i < read; i++ )
        {
            if( buff[i] == ',' )
            {
                comma_found = 1;
                break;
            }
            else if( buff[i] == '\n' )
               buff[i] = ' ';
        }
 
        if( !comma_found )
        {
            puts( buff );
            putchar( '\n' );
        }
        else
            puts( "[SENTENCE SKIPPED]\n" );
    }
 
    fclose( in );
 
    puts( "\n[EOF]" );
 
    return 0;
}
Добавлено через 15 секунд
опоздал
0
Заблокирован
Автор FAQ
19.09.2011, 15:31 13
Цитата Сообщение от talis Посмотреть сообщение
if( ch == '.' )
- других окончаний предложений нет???Ведь есть ещё '!' '?' почему бы сразу это не учитывать???
0
794 / 546 / 61
Регистрация: 11.05.2010
Сообщений: 1,298
Записей в блоге: 1
19.09.2011, 15:41 14
Цитата Сообщение от -=ЮрА=- Посмотреть сообщение
других окончаний предложений нет???Ведь есть ещё '!' '?' почему бы сразу это не учитывать???
-=ЮрА=-, ладно. У меня это решается простым оператором &&.

Почему вы читаете текст в двоичном режиме? Что будет, если вам попадётся огромный файл, больше размера памяти, которую может выделить вам система? Да и вообще, ftell не учтёт файлы больше 2GB.

Ну и так далее. Давайте и дальше искать недоработки в программах друг друга. Особенно в такой манере. Я смотрю, вам это нравится.
0
nxnx
19.09.2011, 15:42
  #15

Не по теме:

talis,
-=ЮрА=-,
вы соревнование что ли устроили, кто быстрее запостит свою версию кода?

0
talis
19.09.2011, 15:46
  #16

Не по теме:

nxnx, да нет, вроде. По крайней мере я ;)

0
sandye51
19.09.2011, 15:50
  #17

Не по теме:

nxnx, просто -=ЮрА=-'e сделали пару замечаний в пред. темах, он их неадекватно воспринял, теперь будет пытаться докапаться в ответ :-)

2
Заблокирован
Автор FAQ
19.09.2011, 17:57 18
Не по теме
talis,
Цитата Сообщение от talis Посмотреть сообщение
Почему вы читаете текст в двоичном режиме? Что будет, если вам попадётся огромный файл, больше размера памяти, которую может выделить вам система? Да и вообще, ftell не учтёт файлы больше 2GB.
- в своей жизни текстовик 2GB встречали???"rb" позволяет корректно разбирать "\r\n" в текстовом режиме иногда бывают грабли

Цитата Сообщение от talis Посмотреть сообщение
Ну и так далее. Давайте и дальше искать недоработки в программах друг друга. Особенно в такой манере. Я смотрю, вам это нравится.
- это нравится не мне например есть люди
Цитата Сообщение от sandye51 Посмотреть сообщение
Не по теме:
nxnx, просто -=ЮрА=-'e сделали пару замечаний в пред. темах, он их неадекватно воспринял, теперь будет пытаться докапаться в ответ :-)
, ну а у вас частенько поддакивание им происходит. Пиши те мирно как это я делаю (и не ищите красных карточек за офтоп как некоторые...) и вам слова никто не скажетЯ приветсвую критику там где она уместна + экономлю на хедерах и предпочитаю Си в форточках, кому ближе пингвин с плючам, ну пиши себе на здоровье других не трогай
0
19.09.2011, 17:57
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
19.09.2011, 17:57
Помогаю со студенческими работами здесь

Считать текст с файла, вывести только предложения, содержащие заданное слово
Написать программу, которая считывает текст из файла и выводит на экран только предложения,...

Считать текст из файла и вывести на экран только предложения, не содержащие запятых
нужно написать программу на джаве,которая считывает текст из файла и выводит на экран только...

Считать текст из файла и вывести на экран только предложения, начинающиеся с тире
Помогите пожалуйста, не знаком с работой с файлами в плюсах и не силен в работе со строками. Нужно...

Считать текст из файла и вывести на экран только предложения, не содержащие запятых
Написать программу, которая считывает текст из файла и выводит на экран только предложения, не...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
18
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru