Поиск в файле txt

231
23 мая 2018, 03:20

Хочу сделать поиск в файле по количеству комнат и диапазону цен, всё по запросу пользователя. Есть пока лишь это

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <sstream>
#include <vector>
using namespace std;
class RealtorOffice
{
public:
string Location;
string LocOfDeclarant;
int NumberOfRooms;
int Price;
};
void print(RealtorOffice &obj)
{
    cout << "Location: "<<obj.Location<<"\nLocation of declarant: "<<obj.LocOfDeclarant<<"\nNumber of rooms: "<<obj.NumberOfRooms<<"\nPrice: "<<obj.Price<<"\n\n"<<endl;
}
void input();
void output();
//void search_by_num();
//void search_by_price()
int menu()
{
cout << " ::: YOOO ::: " <<endl<< endl;
cout << "****************************************************" << endl << endl;
cout << ":::Menu:::\n\n";
int choice;
cout<<"0. Exit"<<endl
<<"1. All"<<endl
<<"2. Search by number of rooms"<<endl
<<"3. Search by price"<<endl
<<"Ваш вибір ->";
cin>>choice;
return choice;
}
void input()
{
ofstream file_obj;
file_obj.open("Input.txt", ios::app);
RealtorOffice obj;
obj.Location = "New_York";
obj.LocOfDeclarant = "LA";
obj.NumberOfRooms = 1;
obj.Price = 150;
file_obj << obj.Location << " ";
file_obj << obj.LocOfDeclarant << " ";
file_obj << obj.NumberOfRooms << " ";
file_obj << obj.Price << endl;
obj.Location = "Chicago";
obj.LocOfDeclarant = "Chicago";
obj.NumberOfRooms = 2;
obj.Price = 250;
file_obj << obj.Location << " ";
file_obj << obj.LocOfDeclarant << " ";
file_obj << obj.NumberOfRooms << " ";
file_obj << obj.Price << endl;
}
void output(vector<RealtorOffice> &v)
{
ifstream file_obj;
file_obj.open("Input.txt");
RealtorOffice obj;
for(string s; getline(file_obj,s);)
    {
    stringstream stream(s);
    stream >> obj.Location;
    stream >> obj.LocOfDeclarant;
    stream >> obj.NumberOfRooms;
    stream >> obj.Price;
    v.push_back(obj);
    print(obj);
    }
}
int main()
{
input();
vector<RealtorOffice> v;
vector<RealtorOffice> res;

int choice;
do
{
    choice = menu();
    switch(choice)
    {
        case 0: cout<<"Bye"<<endl;
        break;
        case 1:output(v);
        break;
       /* case 2:search_by_num();
        break;*/
        /*case 3:search_by_price();
        break;*/
    }
}
while(choice!=0);
return 0;
}

пробовала что-то накидать сама, но оно криво работает

void search(vector<RealtorOffice> &v,vector<RealtorOffice> &result, int num_of_room)
{
for(RealtorOffice &x : v)
{
    if(x.NumberOfRooms == num_of_room)
    {
        result.push_back(x);
    }
}
}

Помогите кто чем может) на крайняк видео, ресурсы, большое спасибо (про оплошности кода знаю, только новичок)

Answer 1

Вот код в котором можно найти и заменить строку, результат выдается в консоль:

#include <stdio.h>
#include <string.h>
/* stf - что ищем; rtf - на что меняем; fpath - путь к файлу; str - стока текста*/
int main ()
{
char file_path[40] = { 0 }, stf[255] = { 0 }, rtf[255] = { 0 }, str[255] = { 0 };
FILE* file = NULL;
do
{
printf("Enter file path: ");
fgets(file_path, 40, stdin);
file_path[strlen(file_path) - 1] = '\0';
file = fopen(file_path, "r+");
}
while(file == NULL);
printf("Enter text to find: ");
fgets(stf, 255, stdin);
stf[strlen(stf) - 1] = '\0';
printf("Enter text to replace: ");
fgets(rtf, 255, stdin);
rtf[strlen(rtf) - 1] = '\0';
while(fgets(str, 255, file) != NULL)
{
char* tmp_ptr = strstr(str, stf);
while(tmp_ptr != NULL)
{
    char tmp_str[255];
    strcpy(tmp_str, tmp_ptr + strlen(stf));
    strcpy(str + strlen(str) - strlen(tmp_ptr), rtf);
    strcat(str, tmp_str);
    tmp_ptr = strstr(str, stf);
}
printf("%s", str);
}
fclose(file);
getchar();
return 0;
}
READ ALSO
epoll полностью грузит ядро?

epoll полностью грузит ядро?

Вызов epoll_wait() по сути производит активное ожидание на переданных дескрипторах в течении таймаутаВопрос, то есть он полностью убивает одно...

205
Настройка клиента и сервера, ZeroMQ

Настройка клиента и сервера, ZeroMQ

Возникла необходимость написать обмен данными, между python и C++Работает все в локал хосте

215
Синтаксис оператора new

Синтаксис оператора new

Вот здесь предоставлен прототип оператора new :

264
ROI треугольной/трапециевидной формы

ROI треугольной/трапециевидной формы

Как задать в С++ d OpenCV 3 ROI треугольной или трапециевидной формы?

227