Прочтение текстовых файлов
Суть вопроса:Как вывести на экран название туроператора, и цену путевки, если название курорта начинается на «Трус», а количество дней более 18. Вот что написано в текстовом файле 1) Название курорта 2)Цена 3)Название туроператора 4)колличество дней
Трустровка:10000 Феерия@24
Лазаревское:20000 Альянс@10
Гострусо:30000 Сиеста@19
Трустоба:5900 Корал@17
Алдер:6780 Веди@20
Трустервазия:25000 Туристическая@20
Мой код:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include<fstream>
#include <WINDOWS.h>
using namespace std;
struct pytivka
{
char nazvaniekyrorta[100];
int cenapytivki[100];
char nazvanieoperatora[100];
int colvodnei[100];
}object;
int main()
{
setlocale(LC_ALL, "Ru");
ifstream phile("pytivka.txt");
if (!phile.is_open())
{
cout << "Ошибка открытия файла!";
return 0;
}
pytivka data;
char buffer[256];
const char pattern[] = "Трус";
while (phile.getline(buffer, 256))
{
char* token = strtok(buffer, ": @");
strcpy(data.nazvaniekyrorta, token);
token = strtok(NULL, ": @");
data.cenapytivki = atoi(token);
token = strtok(NULL, ": @");
strcpy(data.nazvaniekyrorta, token);
token = strtok(NULL, ": @");
data.colvodnei = atoi(token);
if (strncmp(data.nazvaniekyrorta, pattern, sizeof(pattern) - 1) == 0 && data.colvodnei > 18 )
{
cout << data.nazvanieoperatora << data.cenapytivki;
}
}
phile.close();
}
Ответы (1 шт):
Автор решения: wololo
→ Ссылка
Да воспользуйтесь вы, наконец, возможностями C++:
#include <iostream>
#include <fstream>
#include <clocale>
#include <string>
#include <cstdlib>
#include <locale>
using std::cout;
using std::endl;
bool is_space(std::ifstream::int_type symbol, const std::locale& loc)
{
return ( symbol != std::ifstream::traits_type::eof() &&
std::isspace(std::ifstream::traits_type::to_char_type(symbol), loc) );
}
int main()
{
std::setlocale(LC_ALL, "");
std::ifstream file("pytivka.txt");
if (!file.is_open())
{
cout << "Ошибка открытия файла!";
return EXIT_FAILURE;
}
const auto loc = file.getloc();
while (true)
{
//Считываем пробелы перед названием курорта
while (is_space(file.peek(), loc))
file.get();
std::string spa;
std::getline(file, spa, ':');
int price;
file >> price;
//Считываем пробелы перед названием туроператора
while (is_space(file.peek(), loc))
file.get();
std::string tour;
std::getline(file, tour, '@');
int days;
file >> days;
if (file.fail())
break;
if (spa.find("Трус") == 0 && days > 18)
cout << tour << " " << price << endl;
}
file.close();
}
Приведённый код у меня вывел:
Феерия 10000
Туристическая 25000