Код:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
#define O_F_NAME "output.txt"
int main()
{
/* Variables */
char need, it;
char f_name[80];
ios::pos_type pos;
int min_num = 0, max_num, i = 1;
/* Introduction */
cout << "Enter the file: ";
cin.get(f_name, 80);
ifstream in(f_name, ios::in);
if (!in) {
cout << "Error in opening file.\n\n";
exit(1);
}
cout << "\nEnter symbol for find: ";
cin >> need;
ofstream out(O_F_NAME, ios::out);
if (!out) {
cout << "Error in creating output file.\n\n";
exit(2);
}
/* Make head of output file */
out << "Result of searching for \"" << need << "\":\n\n";
/* Find max number of symbol */
in.seekg(0, ios::end);
pos = in.tellg();
max_num = (int)pos - 1; // pos - number of end
in.seekg(0, ios::beg);
/* Find 'it', write out to the file */
while (!in.eof()) {
it = (char)in.peek(); // ios::cur++
if (it != need) {
it = (char)in.get();
continue;
}
out << i++ << ") '";
pos = in.tellg(); // cur number
if ((int)pos > min_num) {
in.seekg(-1, ios::cur);
out << (char)in.get();
}
out << (char)in.get();
if (in.eof()) continue;
if ((int)pos < max_num) {
out << (char)in.get();
}
out << "'\n";
}
cout << "\nSuccess. Results of searching placed in \"" << O_F_NAME << "\"\n\n";
out.close();
in.close();
system("pause");
return 0;
}
Как справедливо заметили, я не указал, что хочу видеть на выходе:) Должно быть так: [x][need][y]
- где x
- символ слева от искомого, y
- справа(если need
первый или последний символ в файле, то "обрамление" опускается).
Если need
= -
(ищим тире) вывод программы(применил на книгу: book.txt) примерно такой:
1) 'tor'
2) 'f-t'
3) 'f-t'
4) 'h-d'
5) 'h-d'
6) 'n-k'
7) '-te'
8) 'f-c'
9) 's.
'
...
(Откуда, например, взялась строка 1) 'tor'
если искали -
?)
Мне казалось алгоритм исключает обрабатывание всех символов кроме нужного здесь:
it = (char)in.peek(); // ios::cur++
if (it != need) {
it = (char)in.get();
continue;
}
Программа должна искать символ, который задаёт пользователь, в файле, который он вводит. Она работает, но странно(выводит неожиданные "три символа"). На маленьких(созданных вручную) файлах всё нормально, но на книге даёт такой вывод(смотрите выше). Не могу понять, чем это может быть обусловлено?