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

Найти строку в текстовом файле

16.09.2016, 15:35. Показов 2561. Ответов 5
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Написать линейную программу без использования функций и процедур. В программе должно быть реализовано меню выбора действий: добавление записи, поиск записи, выход. Программы должны работать с типизированным файлом. В алгоритме должно быть предусмотрены две основные операции: добавление новой записи и поиск записи по некоторому запросу, соответствующему тематике варианта задания (Каталог дисков с ПО).

Проблема: в файл записывается структура, как совершить поиск записи по запросу, допустим по POname?
Суть: вводим с клавиатуры имя ПО, программа возвращает всю остальную часть структуру содержащую это имя. (Disktype, POname, POtype, POdeveloper)

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <conio.h>
#include <stdio.h>
#include <iostream.h>
#include <fstream.h>
#include <conio.c>
typedef struct _DISKS
{
   char Disktype[10];
   char POname[20];
   char POtype[20];
   char POdeveloper[20];
}DISKS, *PDISKS;
 
char path[] = "disks.txt";
DISKS st;
 
void main()
{
 
char choice;
        fstream file;
        char a;
        char b;
        char c;
        char d;
 
    do
    {
        clrscr();
                cout<<"1 - add new record\n";
                cout<<"2 - search by PO name\n";
                cout<<"3 - search by PO type\n";
                cout<<"4 - search by PO developer\n";
                cout<<"5 - search by Disktype\n";
        switch(choice = getch())
        {
            case '1':
                        {
                                file.open(path,ios::app);
                                if(!file)
                                {
                                        cout<<"File could not be opened!!!\n";
                                }
                                else
                                {
                                        cout<<"Disktype: ";cin>>st.Disktype;
                                        cout<<"POname: ";cin>>st.POname;
                                        cout<<"POtype: ";cin>>st.POtype;
                                        cout<<"POdeveloper: ";cin>>st.POdeveloper;
                                        file.write((char*)&st,sizeof(DISKS));
                                        file.close();
                                }
                                getch();
                                break;
                        }
            case '2':
                        {
                                file.open(path,ios::in);
                                if(!file)
                                {
                                        cout<<"File could not be opened!!!\n";
                                }
                                else
                                {
                                        cout<<"Enter PO name: ";
                                         //??????????????????????????
                                         //????????????????????????
                                         //Naiti slovo, vvedennoe polzovatelem v faile
                                         //i vivesti ost chast' struct
                                         
                                         cout<<"Disktype: "<<st.Disktype;<<endl;
                                         cout<<"POname: "<<st.POname<<endl;
                                         cout<<"POtype: "<<st.POtype<<endl;
                                         cout<<"POdeveloper: "<<st.POdeveloper<<endl;
                                }
                                getch();
                                break;
                        }
             case '3':
                        {
                                file.open(path,ios::in);
                                if(!file)
                                {
                                        cout<<"File could not be opened!!!\n";
                                }
                                else
                                {
                                        cout<<"Enter PO type: ";
                                         
                                        cout<<"Disktype: "<<st.Disktype;<<endl;
                                        cout<<"POname: "<<st.POname<<endl;
                                        cout<<"POtype: "<<st.POtype<<endl;
                                        cout<<"POdeveloper: "<<st.POdeveloper<<endl;
                                }
                                getch();
                                break;
                        }      
              case '4':
                        {
                                file.open(path,ios::in);
                                if(!file)
                                {
                                        cout<<"File could not be opened!!!\n";
                                }
                                else
                                {
                                        cout<<"Enter PO developer: ";
                                         
                                        cout<<"Disktype: "<<st.Disktype;<<endl;
                                        cout<<"POname: "<<st.POname<<endl;
                                        cout<<"POtype: "<<st.POtype<<endl;
                                        cout<<"POdeveloper: "<<st.POdeveloper<<endl;
                                }
                                getch();
                                break;
                        }
                case '5':
                        {
                                file.open(path,ios::in);
                                if(!file)
                                {
                                        cout<<"File could not be opened!!!\n";
                                }
                                else
                                {
                                        cout<<"Enter Disktype: ";
                                         
                                        cout<<"Disktype: "<<st.Disktype;<<endl;
                                        cout<<"POname: "<<st.POname<<endl;
                                        cout<<"POtype: "<<st.POtype<<endl;
                                        cout<<"POdeveloper: "<<st.POdeveloper<<endl;
                                }
                                getch();
                                break;
                        }                        
        }
    }
    while(choice != 27);
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
16.09.2016, 15:35
Ответы с готовыми решениями:

Как найти строку Чили в текстовом файле ?
и 1 вывести ее на консоль 2 вывести ее столицу Например в текстовом файле список стран Канада...

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

Как изменить определенную строку в текстовом файле?
Я создаю программу Contacts. У каждого контакта есть свои данные: id, name... и т.д. Но это не...

Замена подстроки в текстовом файле на другую строку
Разработайте программу replace.exe, выполняющую замену подстроки в текстовом файле на другую...

5
Модератор
Эксперт CЭксперт С++
5284 / 2371 / 342
Регистрация: 20.02.2013
Сообщений: 5,770
Записей в блоге: 20
16.09.2016, 18:10 2
skape, задание нереализуемо ни на Си, ни на C++. У Вас использована функция main(), что противоречит условию задачи.
0
nd2
3437 / 2816 / 1249
Регистрация: 29.01.2016
Сообщений: 9,426
16.09.2016, 20:25 3
Цитата Сообщение от skape Посмотреть сообщение
Проблема: в файл записывается структура, как совершить поиск записи по запросу, допустим по POname?
Читаешь последовательно структуры из файла, проверяешь нужное поле на совпадение, если нашёл - выводишь структуру.
1
Модератор
Эксперт CЭксперт С++
5284 / 2371 / 342
Регистрация: 20.02.2013
Сообщений: 5,770
Записей в блоге: 20
17.09.2016, 20:35 4
skape, как раз недавно с ребятами обсуждали красивый макрос:

Вариант со структурами

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
// Сортировка массива объектов пользовательского типа (структуры) по заданному полю:
 
#define by(x) [](const auto& a, const auto& b) { return a.x < b.x; }
 
#include <iostream>
#include <algorithm>
#include <random>
 
struct Item
{
    int a_;
    int b_;
 
    Item()
    {
        std::random_device id;
        std::mt19937 mt( id() );
        std::uniform_int_distribution<int> dist(10, 99);
 
        a_ = dist( mt );
        b_ = dist( mt );
    }
 
    friend std::ostream & operator<<( std::ostream & os, const Item & i )
    {
        os << i.a_ << " "
           << i.b_ << " ";
 
        return os;
    }
};
 
 
int main()
{
    const size_t N = 10;
 
    Item arr[N];
 
    std::cout << "Before:\n";
 
    for (const auto & elem : arr)
        std::cout << elem << "\n";
 
    std::sort( arr, arr + N, by( a_ ) );
 
    std::cout << "\nAfter:\n";
 
    for (const auto & elem : arr)
        std::cout << elem << "\n";
 
    return 0;
}


Вариант со классами

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
// Сортировка массива объектов пользовательского типа (классы) по заданному полю:
 
#define by(x) [](const auto& a, const auto& b) { return a.x < b.x; }
 
#include <iostream>
#include <algorithm>
#include <random>
 
class Item
{
    int a_;
    int b_;
 
public:
    Item()
    {
        std::random_device id;
        std::mt19937 mt( id() );
        std::uniform_int_distribution<int> dist(10, 99);
 
        a_ = dist( mt );
        b_ = dist( mt );
    }
 
    friend std::ostream & operator<<( std::ostream & os, const Item & i )
    {
        os << i.a_ << " "
           << i.b_ << " ";
 
        return os;
    }
 
    int a() const { return a_; } // геттер поля a_
    int b() const { return b_; } // геттер поля b_
};
 
 
int main()
{
    const size_t N = 10;
 
    Item arr[N];
 
    std::cout << "Before:\n";
 
    for (const auto & elem : arr)
        std::cout << elem << "\n";
 
    std::sort
        (
            arr,
            arr + N,
            by( a() )
        );
 
    std::cout << "\nAfter:\n";
 
    for (const auto & elem : arr)
        std::cout << elem << "\n";
 
    return 0;
}


Идея честно стырена отсюда.
1
0 / 0 / 1
Регистрация: 16.09.2016
Сообщений: 4
20.10.2016, 21:15  [ТС] 5
Сделал.

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <iostream.h>
#include <fstream.h>
#include <conio.c>
#include <cstring>
#include <stdlib.h>
#include <string.h>
#include <string>
#define N 20
using namespace std;
int main()
{
    
  FILE *file_d;  
    struct disks              
        {
            int  number, date;
            char POname[20];
            char Disktype[20];
            char POtype[20];
            char POdeveloper[20];
        } disk[N]={};
  int i,j,l,a;                 
  int choice;                  
  int check;                 
  int flag=0;                 
    do
        {
            flag++;            
            if (flag<2)        
                {   system("color F0");
                    cout<<"\n   Make a choice!\a\n\n";  
                    cout<<"  1 - Show all records.\n";
                    cout<<"  2 - Add new record.\n";   
                    cout<<"  3 - Delete file.\n";
                    cout<<"  4 - Make new file(if file missing).\n"; 
                    cout<<"  5 - Search by name of PO.\n"; 
                    cout<<"  6 - Search by type of disc.\n"; 
                    cout<<"  7 - Search by type of PO.\n"; 
                    cout<<"  8 - Search by developer of PO.\n"; 
                    cout<<"  9 - Show all records by date over than.\n\n";  
                    cout<<"  10 - Close programm.\n";  
                    cout<<"___________________________________________\n";  
                    
                }
            cin>>choice; 
 
            switch(choice) 
                {
                    
                    case 1: 
                        if ((file_d = fopen("labfile.txt", "rb")) == NULL) 
                            cout<<"File couldn't be opened. Make new file!\a\n";            
                        else 
                            {         
                                for(j=0; !feof(file_d); j++) 
                                    fread(&disk[j], sizeof(struct disks), 1, file_d);
                                    fclose(file_d);
                                    j--;
                                    cout<<"                  All records\a\n\n\n";
                                for(i=0; i<j; i++)  
                                    printf("%2d|%15s%15s%15s%15d%15s\n", disk[i].number, disk[i].Disktype, disk[i].POname, disk[i].POtype, disk[i].date, disk[i].POdeveloper); 
              }                              
                    break;
                    
                    
                    case 2: 
        
                        if ((file_d = fopen("labfile.txt", "rb")) == NULL)
                            cout<<"File couldn't be opened. Make new file!\a\n";            
                        else
                            {
                                for(i=0; !feof(file_d); i++)
                                    fread(&disk[i], sizeof(struct disks), 1, file_d);
                                    fclose(file_d);
                                    cout<<"Fill structure, please.\a\n";
                                    l=1;
                                    i--;
                                for(a=i; l!=0; i++) 
                                    {
                                        disk[i].number = i+1;
                                        cout<<"\nWrite information about disk "<<i+1<<":\n"<<endl;
                                        cout<<"Type of disc(cd,dvd...): "; gets(disk[i].Disktype);
                                        cout<<"PO name: "; gets(disk[i].POname);
                                        cout<<"Type of PO: "; gets(disk[i].POtype);
                                        cout<<"Date of creation: "; scanf ("%d%*c",&disk[i].date);
                                        cout<<"PO developer: "; gets(disk[i].POdeveloper);
                                        cout<<"0 - Go to menu.\a\n";
                                        cout<<"Random number - continue fill structure\n";
                                        scanf ("%d%*c",&l);
                                    }
                            file_d = fopen("labfile.txt", "ab");
                            for(; a<i; a++)
                                fwrite(&disk[a], sizeof(struct disks), 1, file_d);
                                fclose(file_d);    
                            } 
              
                        break;
              
              
                    case 3: 
                        cout<<"File delete!\n\a";
                        remove("labfile.txt");
                        break; 
                   
                   
                    case 4: 
             
                        if ((file_d = fopen("labfile.txt", "rb")) == NULL)
                            {
                                cout<<"Fill structure, please.\a\n";
                                l=1;
                        for(i=0; l!=0; i++)
                            {
                                disk[i].number = i+1;
                                cout<<"\nWrite information about disk "<<i+1<<":\n"<<endl;
                                cout<<"Type of disc(cd,dvd...): "; gets(disk[i].Disktype);
                                cout<<"PO name: "; gets(disk[i].POname);
                                cout<<"Type of PO: "; gets(disk[i].POtype);
                                cout<<"Date of creation: "; scanf ("%d%*c",&disk[i].date);
                                cout<<"PO developer: "; gets(disk[i].POdeveloper);
                                cout<<"0 - Go to menu.\a\n";
                                cout<<"Random number - continue fill structure\n";
                                scanf ("%d%*c",&l);
                            }    
                       file_d = fopen("labfile.txt", "wb");
                       for(j=0; j<i; j++)
                            fwrite(&disk[j], sizeof(struct disks), 1, file_d);
                            fclose(file_d);
                            }
                        else
                            cout<<"File already exists!\a\n";
                        break;  
              
                    case 5:                  
                        if ((file_d = fopen("labfile.txt", "rb")) == NULL)
                            cout<<"File couldn't be opened. Make new file!\a\n";           
                        else
                            {
                                for(j=0; !feof(file_d); j++)
                                    fread(&disk[j], sizeof(struct disks), 1, file_d);
                                    fclose(file_d);
                                check=true;
                                string str;
                                cout<<"Enter name of PO: ";
                                cin>>str;
                                cout<<"\n\nStruct with POname: \a\n";
                                for(i=0; i<j; i++)
                                    {
                                        if (disk[i].POname==str)
                                            {
                                                printf("%2d|%15s%15s%15s%15d%15s\n", disk[i].number, disk[i].Disktype, disk[i].POname, disk[i].POtype, disk[i].date, disk[i].POdeveloper); 
                                                check=false;
                                            }
                                    }
                                if (check)
                                cout<<"Nothing found.";
                            }
                            cout<<endl;               
                        break;
                    case 6:           
                        if ((file_d = fopen("labfile.txt", "rb")) == NULL)
                            cout<<"File couldn't be opened. Make new file!\a\n";           
                        else
                            {
                                for(j=0; !feof(file_d); j++)
                                    fread(&disk[j], sizeof(struct disks), 1, file_d);
                                    fclose(file_d);
                                check=true;
                                string str;
                                cout<<"Enter type of disc: ";
                                cin>>str;
                                cout<<"\n\nStruct with Disktype: \a\n";
                                for(i=0; i<j; i++)
                                    {
                                        if (disk[i].Disktype==str)
                                            {
                                                printf("%2d|%15s%15s%15s%15d%15s\n", disk[i].number, disk[i].Disktype, disk[i].POname, disk[i].POtype, disk[i].date, disk[i].POdeveloper); 
                                                check=false;
                                            }
                                    }
                                if (check)
                                cout<<"Nothing found.\a";
                            }
                            cout<<endl;               
                        break;
                    case 7:            
                        if ((file_d = fopen("labfile.txt", "rb")) == NULL)
                            cout<<"File couldn't be opened. Make new file!\a\n";           
                        else
                            {
                                for(j=0; !feof(file_d); j++)
                                    fread(&disk[j], sizeof(struct disks), 1, file_d);
                                    fclose(file_d);
                                check=true;
                                string str;
                                cout<<"Enter type of PO: ";
                                cin>>str;
                                cout<<"\n\nStruct with POtype: \a\n";
                                for(i=0; i<j; i++)
                                    {
                                        if (disk[i].POtype==str)
                                            {
                                                printf("%2d|%15s%15s%15s%15d%15s\n", disk[i].number, disk[i].Disktype, disk[i].POname, disk[i].POtype, disk[i].date, disk[i].POdeveloper); 
                                                check=false;
                                            }
                                    }
                                if (check)
                                cout<<"Nothing found.\a";
                            }
                            cout<<endl;               
                        break;
                    case 8:              
                        if ((file_d = fopen("labfile.txt", "rb")) == NULL)
                            cout<<"File couldn't be opened. Make new file!\a\n";           
                        else
                            {
                                for(j=0; !feof(file_d); j++)
                                    fread(&disk[j], sizeof(struct disks), 1, file_d);
                                    fclose(file_d);
                                check=true;
                                string str;
                                cout<<"Enter developer of PO: ";
                                cin>>str;
                                cout<<"\n\nStruct with POdeveloper: \a\n";
                                for(i=0; i<j; i++)
                                    {
                                        if (disk[i].POdeveloper==str)
                                            {
                                                printf("%2d|%15s%15s%15s%15d%15s\n", disk[i].number, disk[i].Disktype, disk[i].POname, disk[i].POtype, disk[i].date, disk[i].POdeveloper); 
                                                check=false;
                                            }
                                    }
                                if (check)
                                cout<<"Nothing found.\a";
                            }
                            cout<<endl;               
                        break;          
      
                    case 10: 
                    
                        break;          // exit(0);
                        default: cout<<"\nIncorrect choice.\a\n";
                        
                    case 9:    
                        if ((file_d = fopen("labfile.txt", "rb")) == NULL)
                            cout<<"File couldn't be opened. Make new file!\a\n";           
                        else
                            {
                                for(j=0; !feof(file_d); j++)
                                    fread(&disk[j], sizeof(struct disks), 1, file_d);
                                    fclose(file_d);
                                check=true;
                                int n;
                                cout<<"Show all records relise > ";
                                cin>>n;
                                cout<<"\n\nStruct with relise last than "<<n<<" : \a\n";
                                for(i=0; i<j; i++)
                                    {
                                        if (disk[i].date>=n)
                                            {
                                                printf("%2d|%15s%15s%15s%15d%15s\n", disk[i].number, disk[i].Disktype, disk[i].POname, disk[i].POtype, disk[i].date, disk[i].POdeveloper); 
                                                check=false;
                                            }
                                    }
                                if (check)
                                cout<<"Nothing found.\a";
                            }
                            cout<<endl;               
                        break;  
               
}//switch end
}// do end
while (choice!=10);
remove("labfile.txt");
}                                        // main end
0
Модератор
Эксперт CЭксперт С++
5284 / 2371 / 342
Регистрация: 20.02.2013
Сообщений: 5,770
Записей в блоге: 20
21.10.2016, 22:03 6
Цитата Сообщение от skape Посмотреть сообщение
Сделал.
Чувак... Зачем ты так со мной?
Миниатюры
Найти строку в текстовом файле  
0
21.10.2016, 22:03
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
21.10.2016, 22:03
Помогаю со студенческими работами здесь

В текстовом файле удалить последнюю строку результат записать в другой файл
#define _CRT_SECURE_NO_WARNINGS #include &lt;iostream&gt; #include &lt;conio.h&gt; #include &lt;string.h&gt;...

Удалить в текстовом файле 1.txt все строки, которые встречаются в текстовом файле 2.txt
например имеется текстовый файл 1.txt c таким содержанием 111 222 333 444 555 и имеется...

Найти в текстовом файле строки по условию
Задача была написать программу. В заданном текстовом файле найти: самую длинную строку. все...

Найти количество строк в текстовом файле
я не можу написати програму для підрахування кількості стрічок в текстовому файлі. чомусь в...


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

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