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


Автор: Leto 19.5.2006, 19:50
Приветы!!! Люди очень нужна помощь.. сдавать надо лабы по программированию, а то сессия скоро а так недопуск будет.. Так вот, помощь состоит в решении следующей задачки на языке Си++:
Написать программу, которая считывает текст из файла “text.txt” и выводит на экран только предложения, содержащие введенное с клавиатуры слово. В файле text.txt дописать информацию о том, сколько предложений было найдено.
вотЪ такая вот. Если кому не трудно, посмарите плиzzz  smile  

Автор: Rockie 21.5.2006, 14:17
Будем считать, что все предлжения начинаются с большой буквы и заканчиваются точкой. Считываем слова из файла и сравниваем с заданным. некоторые слова считываются из потока с точкой или запятой в конце слова. чтобы слова правильно сравнивались, эти знаки препинания убираются. в start_position запоминаем, где в файле началось предложение (где большая буква). если слово нашлось, перемещаемся на start_position и печатаем предложение до точки.
Код
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <string.h>
#include <fstream.h>

int main(){
  char control_word[] = "file";      // search word here
  char word[20];                     // word array
  int start_position = 0;

  clrscr();

  for(int i=0;i<10;i++)             // set it to null, can be deleted
    word[i]=' ';

  ifstream read_file("myfile.txt"); // open file
  if (!read_file) return 0;

   while(!read_file.eof())
    { read_file>>word;                // read word from file

      if( word[0]>=65 && word[0]<=90 )  // if letter is big
       {  start_position = (int)read_file.tellg() - (int)strlen(word); // remember where proposition begins
       }

      if(word[(int)strlen(word)-1]== '.' || word[(int)strlen(word)-1]== ',') // we can get word with '.' or ',' on the end,
     { word[(int)strlen(word)-1]='\0';                                   // we should change it to '\0'
     }


      if(strcmp(word,control_word)==0)          // compare words

    { read_file.seekg(start_position);    // go where proposition starts
      while(word[(int)strlen(word)-1]!= '.')
       { read_file>>word;
         cout<<word<<' ';
       }
       cout<<'\n';
    }
    }

   read_file.close();
   getch();
   return 0;
}

содержимое файла myfile.txt (цифрами отмечены предложения с конрольным словом "file" )
Цитата
The next character that will be.

This is the file associated with stream 1.

The function then increments the associated file 2 pointer (if defined) to point to the next character.

Aasasad.

Dsfdsfsd.

If the stream is at end of 3 file, the end-of-file indicator for the stream is set.

The feof function returns a nonzero 4  value after the first read operation that attempts to read past the end of the file.

Sdfdsfdsg.

Vasya pupkin was here.

It returns 0 if the current position is not end of file 5 .

There is no error retur 6  n file, jk.


P.S.: в BCBuilder 6 (int)read_file.tellg()  возвращает -1, лучше юзать другой компилятор. 

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