Консультация № 198649
20.05.2020, 02:10
0.00 руб.
0 1 1
Здравствуйте, уважаемые эксперты! Прошу вас ответить на следующий вопрос: Дан файл f. Создать два файла, записав в первый из них все четные числа, расположив их в порядке возрастания, а во второй – все нечетные, расположив их в порядке убывания. Работаю в программе С++, среда разработки - CodeBlocks.

Обсуждение

давно
Советник
400484
472
21.05.2020, 11:58
общий
это ответ
Здравствуйте, yanastegantseva.com!
Вариант кода:
Код:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;

void InFile(vector<int> &chet, vector<int> &nechet);
bool NumberCheck(char *word);
void OutFile(vector<int> v, bool chet);

int main()
{
vector<int> chet;
vector<int> nechet;

InFile(chet, nechet);

OutFile(chet, true);
OutFile(nechet, false);

return 0;
}

void InFile(vector<int> &chet, vector<int> &nechet)
{
string line;

ifstream in("f.txt"); // окрываем файл для чтения
if (in.is_open())
{
char word[256] = {};
while (getline(in, line))
{
cout << "line: " << line << endl;
stringstream x; //Создание потоковой переменной
x << line;

while (x >> word)
{
if (NumberCheck(word))
{
int i = atoi(word);
if (i % 2 == 0)
chet.push_back(i);
else
nechet.push_back(i);
}
}
}
}
in.close(); // закрываем файл
}

bool NumberCheck(char *word)
{
int amountOfSymbol = 0;
while (word[amountOfSymbol] != '\0')
{
if(word[amountOfSymbol] < 48 || word[amountOfSymbol] > 57)
{
if (word[amountOfSymbol] == '-' || word[amountOfSymbol] == '+')
{
amountOfSymbol++;
continue;
}

return false;
}
amountOfSymbol++;
}

return true;
}

void OutFile(vector<int> v, bool chet)
{
string file = chet ? "chet.txt" : "nechet.txt";
sort(begin(v), end(v));
ofstream fout(file, ios_base::trunc); // создаём объект класса ofstream для записи и связываем его с файлом
if (fout.is_open())
{
for (const auto a : v)
{
fout << a << " ";
}
}
fout.close();
}
Форма ответа