Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 17.12.2019, 16:47   #1
Skynet12341
Новичок
Джуниор
 
Регистрация: 17.05.2017
Сообщений: 2
По умолчанию Конвертер систем счисления.

Нужно сделать консольный конвертер систем счисления.
При вводе целого числа, если переводило в двоичную, восьмеричную и шестнадцатеричную.
При входе в программу должно быть 3 режима работы.
-Интерактивный - данные в консоль с клавиатуры, результаты так же выводятся на консоль.
-Полуинтерактивный - включается, если при запуске программы обнаруживается файл input.txt, в котором находятся входные данные, результаты выводятся на консоль.
-Неинтерактивный - включается, если при запуске программы обнаруживается файл data.txt, в котором находятся входные данные, результаты выводятся в файл output.txt. Окно программы не показывается.

В общем есть два кода, но нужно просто склеить из этого конвертер систем счисления с режимами работы.

Код:
// oop_formula.cpp: определяет точку входа для консольного приложения.
//

#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <windows.h>

using namespace std;

typedef string T_str;
typedef map <T_str, T_str> T_rus_of_eng;


class T_eng_rus_dictionary
{
	T_rus_of_eng rus_of_eng_;
	T_rus_of_eng eng_of_rus_;
	
public:
	
	void add_eng_word_and_rus_translation(T_str eng, T_str rus)
	{
		rus_of_eng_[eng] = rus;
		eng_of_rus_[rus] = eng;
	}
	
	void print_rus_translation(T_str const& eng)
	{
		auto it = rus_of_eng_.find(eng);
		cout << (it == rus_of_eng_.end() ? "Нет перевода." : it->second) << endl;
	}

	void print_eng_translation(T_str const& rus)
	{
		auto it = eng_of_rus_.find(rus);
		cout << (it == eng_of_rus_.end() ? "Нет перевода." : it->second) << endl;
	}
	
	friend
		ostream& operator << (ostream& ostr, T_eng_rus_dictionary const& eng_rus_dict)
	{
		for_each(eng_rus_dict.rus_of_eng_.begin(), eng_rus_dict.rus_of_eng_.end(), [&](auto const& eng_and_rus)
		{
			ostr << eng_and_rus.first << '\t' << eng_and_rus.second << endl;
		}
		);

		return  ostr;
	}
	
	friend
		istream& operator >> (istream& istr, T_eng_rus_dictionary& eng_rus_dict)
	{
		T_str eng;
		T_str rus;

		while ((istr >> eng) && (istr >> rus))
		{
			eng_rus_dict.add_eng_word_and_rus_translation(eng, rus);
		}

		return  istr;
	}
	
};


void choice(int ab, string x) {
	setlocale(LC_ALL, "Russian");
	T_eng_rus_dictionary eng_rus_d;
	ifstream ifile("dictionary.txt");
	T_eng_rus_dictionary new_eng_rus_d;
	ifile >> new_eng_rus_d;
	cout << endl << "Выберите цифру: " << endl << endl;
	cout << "1 - с русского на английский" << endl;
	cout << "2 - с английского на русский" << endl;
	cout << "3 - добавить перевод" << endl;
	cout << endl;
	int sym;
	if (ab != 0) { sym = ab; goto jump; }
lb:
	cout << "Ввод: ";
	cin >> sym;
jump:
	switch (sym) {
	case 1: {
		cout << "Чтобы выйти из режима перевода, введите 4" << endl;
		if (!x.size())cout << "Вводите русские слова для перевода:" << endl;
		for (;;)
		{
			cout << "Русское слово: " << endl;
			T_str rus;
			cin >> rus;
			if (rus == "4")
				break;
			cout << "Английское слово: " << endl;
			new_eng_rus_d.print_eng_translation(rus);
		}
	}
		  break;
	case 2: {
		cout << "Чтобы выйти из режима перевода, введите 4" << endl;
		if (!x.size())cout << "Вводите английские слова для перевода:" << endl;
		for (;;)
		{
			cout << "Английское слово: " << endl;
			T_str eng;
			cin >> eng;
			if (eng == "4")
				break;
			cout << "Русское слово: " << endl;
			new_eng_rus_d.print_rus_translation(eng);
		}
	}
		  break;
	case 3: {
		cout << "Заполнение словаря. Введите количество вводимых записей: ";
		int n = 0;
		cin >> n;

		if (!x.size())for (int i = 0; i < n; ++i)
		{
			cout << "#" << i + 1 << ":" << endl;

			cout << "Английское слово: " << endl;
			T_str eng;
			cin >> eng;
			cout << eng << endl;

			cout << "Русский перевод: " << endl;
			T_str rus;
			cin >> rus;
			cout << rus << endl;

			eng_rus_d.add_eng_word_and_rus_translation(eng, rus);
		}

		ofstream ofile("dictionary.txt", ios::app);
		ofile << eng_rus_d;
	}
		  break;
	
	default: {
		cout << "Ошибка! Такой номер отсутствует!" << endl << endl;
		goto lb;
	}
	}
}

int main() {
	setlocale(LC_ALL, "Russian");
	SetConsoleCP(1251);
	SetConsoleOutputCP(1251);
	char ch = '\0';
	do {
		cout << endl << "Выберите режим работы: " << endl << endl;
		cout << "1 - Интерактивный " << endl;
		cout << "2 - Полуинтерактивный" << endl;
		cout << "3 - Неинтерактивный" << endl;
		cout << "4 - Выход" << endl << endl;

		cout << "Ввод: ";
		cin >> ch;
		cout << endl;
		switch (ch) {
		case '1': {
			choice(0, "");
		}
				break;
		case '2': {
			ifstream x("input.txt"); 
									 
			if (x.is_open()) {
				int a = 0;
				string ss;
				x >> a >> ss;
				choice(a, ss);
			}
			else {
				cout << "Ошибка с открытием файла input.txt" << endl;
			}
			x.close();
		}
				break;
		case '3': {
			ifstream x("input.txt");
			ofstream o("output.txt"); 
			if (x.is_open() && o.is_open()) {
				streambuf* bak;
				int a = 0;
				string ss;
				x >> a >> ss;
				bak = cout.rdbuf();  
				cout.rdbuf(o.rdbuf()); 
				choice(a, ss);
				cout.rdbuf(bak);
				cout << endl << "Данные успешно выведены в файл !" << endl << endl;
			}
			else {
				cout << "Проблема с открытием файлов" << endl << endl;
			}
			x.close();
			o.close();
		}
				break;
		}
	} while (ch != '4');
	return 0;
}
Skynet12341 вне форума Ответить с цитированием
Старый 17.12.2019, 16:47   #2
Skynet12341
Новичок
Джуниор
 
Регистрация: 17.05.2017
Сообщений: 2
По умолчанию

и ещё код

Код:
// oop_formula.cpp: определяет точку входа для консольного приложения.
//

#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <math.h>
#include <cmath>
#include <windows.h>
#include "ConvertSystem.h"
#include "Interface.h"
#include "Source.h"

using namespace std;



class ConvertSystem
{
public:
	ConvertSystem();
	~ConvertSystem();
	int BinarySystem(int number);
	int OctalSystem(int number);
	const char *HDSystem(int number);

public:


	int ConvertSystem::BinarySystem(int number)
	{
		int bin = 0, j;
		for (j = 0; number > 0; j++)
		{
			bin += (number % 2)*pow(10.0, j);
			number /= 2;
		}
		return bin;
	}

	int ConvertSystem::OctalSystem(int number)
	{
		int bin = 0, j;
		for (j = 0; number > 0; j++)
		{
			bin += (number % 8)*pow(10.0, j);
			number /= 8;
		}
		return bin;
	}

	const char * ConvertSystem::HDSystem(int number)
	{
		cout << "Число: " << number << endl;
		const char *bin;
		string binstr = "";
		do
		{
			int r(number % 16);
			if (r > 9) { r += (int)'A' - 10; }
			else { r += (int)'0'; };
			binstr = (char)r + binstr;
			number /= 16;
		} while (number);
		bin = binstr.c_str();

		cout << "В шестнадцатеричной системе: " << bin << endl;
		return bin;
	}
};


void Interface::InterfaceMenu()
{

	cout << "Выберите систему для конвертирования:" << endl;
	cout << " ___________________________________________________" << endl;
	cout << "|               Системы счисления                   |" << endl;
	cout << "|------------|----------------|---------------------|" << endl;
	cout << "| 1.двоичная | 2.восьмеричная | 3.шестнадцатеричная |" << endl;
	cout << "|------------|----------------|---------------------|" << endl;
	cout << "|___________________________________________________|" << endl;
}

void Interface::InterfaceWinInt(int number, int CN, int NM)
{
	cout << "Результат:" << endl;
	if (NM = 1)
	{
		cout << "Число: " << number << endl;
		cout << "В двоичной системе: " << CN << endl;
	}
	else if (NM = 2)
	{
		cout << "Число: " << number << endl;
		cout << "В восьмеричной системе: " << CN << endl;

	}
	else if (NM = 3)
	{
		cout << "Число: " << number << endl;
		cout << "В шестнадцатиричной системе: " << CN << endl;
	}
}

int main() {
	setlocale(LC_ALL, "Russian");
	SetConsoleCP(1251);
	SetConsoleOutputCP(1251);
	char ch = '\0';
	do {
		cout << endl << "Выберите режим работы: " << endl << endl;
		cout << "1 - Интерактивный " << endl;
		cout << "2 - Полуинтерактивный" << endl;
		cout << "3 - Неинтерактивный" << endl;
		cout << "4 - Выход" << endl << endl;

		cout << "Ввод: ";
		cin >> ch;
		cout << endl;
		switch (ch) {
		case '1': {
			int number;
			while (true) {

				cout << "Добрый день, Вы запустили конвертер целых чисел." << endl;

				while (true) // проверка ввода числа, если введено не число пользователь снова должен ввести значение
				{
					cout << "Введите целое число:" << endl;

					cin >> number;
					if (cin.good())
					{
						cin.ignore(10, '\n');
						break;
					}
					cin.clear();
					cout << "Неправильный ввод" << endl;
					cin.ignore(10, '\n');
				}
				Interface inter;
				inter.InterfaceMenu();
				ConvertSystem CS;
				int NumberMenu, ConvertNumber;
				cin >> NumberMenu;
				switch (NumberMenu) {
				case 1:
				{
					ConvertNumber = CS.BinarySystem(number); inter.InterfaceWinInt(number, ConvertNumber, NumberMenu); break;
				}
				case 2:
				{
					ConvertNumber = CS.OctalSystem(number); inter.InterfaceWinInt(number, ConvertNumber, NumberMenu); break;
				}
				case 3:
				{
					const char *ConvertNumberSTR = CS.HDSystem(number);
					break;
				}
				default: cout << "Вы ввели неверное значение" << endl;
				}

			}return 0;
		}
				  break;
		case '2': {
			ifstream x("input.txt");

			if (x.is_open()) {
				int a = 0;
				string ss;
				x >> a >> ss;
				//choice(a, ss);
			}
			else {
				cout << "Ошибка с открытием файла input.txt" << endl;
			}
			x.close();
		}
				  break;
		case '3': {
			ifstream x("input.txt");
			ofstream o("output.txt");
			if (x.is_open() && o.is_open()) {
				streambuf* bak;
				int a = 0;
				string ss;
				x >> a >> ss;
				bak = cout.rdbuf();
				cout.rdbuf(o.rdbuf());
				//choice(a, ss);
				cout.rdbuf(bak);
				cout << endl << "Данные успешно выведены в файл !" << endl << endl;
			}
			else {
				cout << "Проблема с открытием файлов" << endl << endl;
			}
			x.close();
			o.close();
		}
				  break;
		}
	} while (ch != '4');
	return 0;
}
Skynet12341 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Перевод систем счисления Тима4930 Общие вопросы C/C++ 2 02.12.2015 08:52
Перевод Систем Счисления diekster Помощь студентам 10 10.02.2012 19:56
Задача: основания систем счисления WebbMan Помощь студентам 8 23.05.2011 16:10
Перевод систем счисления 16=>10 Alex Cones Общие вопросы Delphi 3 16.05.2009 21:02