КОД #1

Открыто
открыта 4 месяцев назад SemenovDK · комментариев: 0
SemenovDK прокомментировал(а) 4 месяцев назад
Владелец

#include
#include
#include
#include
#include
#include
#include
#include

using namespace std;

// Функции для печати байтов
void print_in_hex(uint8_t byte) {
cout << hex << setw(2) << setfill('0') << static_cast(byte);
}

void print_in_hex(const void* data, size_t size) {
const uint8_t* bytes = static_cast<const uint8_t*>(data);
for (size_t i = 0; i < size; ++i) {
print_in_hex(bytes[i]);
if ((i + 1) % 16 == 0)
cout << endl;
else
cout << " ";
}
cout << endl;
}

void print_in_binary(uint8_t byte) {
cout << bitset<8>(byte);
}

void print_in_binary(const void* data, size_t size) {
const uint8_t* bytes = static_cast<const uint8_t*>(data);
for (size_t i = 0; i < size; ++i) {
print_in_binary(bytes[i]);
if ((i + 1) % 4 == 0)
cout << endl;
else
cout << " ";
}
cout << endl;
}

// Калькулятор побитовых операций
void bitwise_calculator() {
uint16_t a, b;
char op;
cout << "Введите первый операнд: ";
cin >> a;
cout << "Введите оператор (&, |, ^): ";
cin >> op;
cout << "Введите второй операнд: ";
cin >> b;

uint16_t result;
switch (op) {
case '&':
    result = a & b;
    break;
case '|':
    result = a | b;
    break;
case '^':
    result = a ^ b;
    break;
default:
    cout << "Неверный оператор!" << endl;
    return;
}

cout << "Результат в шестнадцатеричном виде: 0x";
print_in_hex(&result, sizeof(result));
cout << endl;

cout << "Результат в двоичном виде: ";
print_in_binary(&result, sizeof(result));
cout << endl;

}

// Структура Student
struct Student {
char name[17];
uint16_t year;
float gpa;
uint8_t gender : 1;
uint8_t courses;
Student* headman;
};

void analyze_student_memory() {
Student students[3] = {
{"Иванов", 2020, 4.5, 1, 5, nullptr},
{"Петров", 2021, 4.2, 1, 4, nullptr},
{"Староста", 2019, 4.8, 0, 6, nullptr}
};

students[0].headman = &students[2];
students[1].headman = &students[2];

cout << "Адрес массива: " << &students << ", Размер массива: " << sizeof(students) << " байт" << endl;
for (size_t i = 0; i < 3; ++i) {
    cout << "Элемент " << i << ": Адрес = " << &students[i] << ", Размер = " << sizeof(students[i]) << " байт" << endl;
}

cout << "Анализ памяти для первого студента:" << endl;
cout << "Имя: Адрес = " << static_cast<void*>(students[0].name)
    << ", Смещение = " << offsetof(Student, name)
    << ", Размер = " << sizeof(students[0].name) << endl;
cout << "Год: Адрес = " << &students[0].year
    << ", Смещение = " << offsetof(Student, year)
    << ", Размер = " << sizeof(students[0].year) << endl;
cout << "Средний балл: Адрес = " << &students[0].gpa
    << ", Смещение = " << offsetof(Student, gpa)
    << ", Размер = " << sizeof(students[0].gpa) << endl;
cout << "Количество курсов: Адрес = " << static_cast<void*>(&students[0].courses)
    << ", Смещение = " << offsetof(Student, courses)
    << ", Размер = " << sizeof(students[0].courses) << endl;

}

// Проверка имени файла и подсчет строк
void file_processing() {
char filename[256];
cout << "Введите имя файла: ";
cin >> filename;

if (strpbrk(filename, "*\"<>?|")) {
    cout << "Имя файла содержит запрещенные символы!" << endl;
    return;
}

char* colon = strchr(filename, ':');
if (colon && (colon != filename + 1 || !isalpha(filename[0]) || *(colon + 1) != '\\')) {
    cout << "Неверное расположение двоеточия!" << endl;
    return;
}

if (!strrchr(filename, '.')) {
    strcat_s(filename, ".txt");
}

ifstream file(filename, ios::binary | ios::ate);
if (!file) {
    cout << "Не удалось открыть файл!" << endl;
    return;
}

streamsize size = file.tellg();
file.seekg(0, ios::beg);

vector<char> buffer(size);
if (!file.read(buffer.data(), size)) {
    cout << "Ошибка чтения файла!" << endl;
    return;
}

char search[256];
cout << "Введите строку для поиска: ";
cin.ignore();
cin.getline(search, sizeof(search));

size_t count = 0;
char* pos = buffer.data();
while ((pos = strstr(pos, search)) != nullptr) {
    ++count;
    pos += strlen(search);
}

cout << "Число вхождений: " << count << endl;

}

int main() {
setlocale(LC_ALL, "Russian");

int choice;
do {
    cout << "Меню:\n";
    cout << "1. Печать данных в шестнадцатеричном и двоичном виде\n";
    cout << "2. Калькулятор побитовых операций\n";
    cout << "3. Анализ памяти структуры Student\n";
    cout << "4. Обработка текстового файла\n";
    cout << "0. Выход\n";
    cout << "Ваш выбор: ";
    cin >> choice;

    switch (choice) {
    case 1: {
        uint8_t data[16] = { 0x1F, 0x2A, 0x3C, 0x4D, 0x5E, 0x6F, 0x7B, 0x8C, 0x9D, 0xAF, 0xBA, 0xCB, 0xDC, 0xED, 0xFE, 0xFF };
        cout << "Шестнадцатеричное представление:" << endl;
        print_in_hex(data, sizeof(data));
        cout << "Двоичное представление:" << endl;
        print_in_binary(data, sizeof(data));
        break;
    }
    case 2:
        bitwise_calculator();
        break;
    case 3:
        analyze_student_memory();
        break;
    case 4:
        file_processing();
        break;
    case 0:
        cout << "Выход из программы." << endl;
        break;
    default:
        cout << "Неверный выбор!" << endl;
    }

} while (choice != 0);

return 0;

}

#include <iostream> #include <iomanip> #include <cstring> #include <fstream> #include <cstdint> #include <bitset> #include <cstddef> #include <vector> using namespace std; // Функции для печати байтов void print_in_hex(uint8_t byte) { cout << hex << setw(2) << setfill('0') << static_cast<int>(byte); } void print_in_hex(const void* data, size_t size) { const uint8_t* bytes = static_cast<const uint8_t*>(data); for (size_t i = 0; i < size; ++i) { print_in_hex(bytes[i]); if ((i + 1) % 16 == 0) cout << endl; else cout << " "; } cout << endl; } void print_in_binary(uint8_t byte) { cout << bitset<8>(byte); } void print_in_binary(const void* data, size_t size) { const uint8_t* bytes = static_cast<const uint8_t*>(data); for (size_t i = 0; i < size; ++i) { print_in_binary(bytes[i]); if ((i + 1) % 4 == 0) cout << endl; else cout << " "; } cout << endl; } // Калькулятор побитовых операций void bitwise_calculator() { uint16_t a, b; char op; cout << "Введите первый операнд: "; cin >> a; cout << "Введите оператор (&, |, ^): "; cin >> op; cout << "Введите второй операнд: "; cin >> b; uint16_t result; switch (op) { case '&': result = a & b; break; case '|': result = a | b; break; case '^': result = a ^ b; break; default: cout << "Неверный оператор!" << endl; return; } cout << "Результат в шестнадцатеричном виде: 0x"; print_in_hex(&result, sizeof(result)); cout << endl; cout << "Результат в двоичном виде: "; print_in_binary(&result, sizeof(result)); cout << endl; } // Структура Student struct Student { char name[17]; uint16_t year; float gpa; uint8_t gender : 1; uint8_t courses; Student* headman; }; void analyze_student_memory() { Student students[3] = { {"Иванов", 2020, 4.5, 1, 5, nullptr}, {"Петров", 2021, 4.2, 1, 4, nullptr}, {"Староста", 2019, 4.8, 0, 6, nullptr} }; students[0].headman = &students[2]; students[1].headman = &students[2]; cout << "Адрес массива: " << &students << ", Размер массива: " << sizeof(students) << " байт" << endl; for (size_t i = 0; i < 3; ++i) { cout << "Элемент " << i << ": Адрес = " << &students[i] << ", Размер = " << sizeof(students[i]) << " байт" << endl; } cout << "Анализ памяти для первого студента:" << endl; cout << "Имя: Адрес = " << static_cast<void*>(students[0].name) << ", Смещение = " << offsetof(Student, name) << ", Размер = " << sizeof(students[0].name) << endl; cout << "Год: Адрес = " << &students[0].year << ", Смещение = " << offsetof(Student, year) << ", Размер = " << sizeof(students[0].year) << endl; cout << "Средний балл: Адрес = " << &students[0].gpa << ", Смещение = " << offsetof(Student, gpa) << ", Размер = " << sizeof(students[0].gpa) << endl; cout << "Количество курсов: Адрес = " << static_cast<void*>(&students[0].courses) << ", Смещение = " << offsetof(Student, courses) << ", Размер = " << sizeof(students[0].courses) << endl; } // Проверка имени файла и подсчет строк void file_processing() { char filename[256]; cout << "Введите имя файла: "; cin >> filename; if (strpbrk(filename, "*\"<>?|")) { cout << "Имя файла содержит запрещенные символы!" << endl; return; } char* colon = strchr(filename, ':'); if (colon && (colon != filename + 1 || !isalpha(filename[0]) || *(colon + 1) != '\\')) { cout << "Неверное расположение двоеточия!" << endl; return; } if (!strrchr(filename, '.')) { strcat_s(filename, ".txt"); } ifstream file(filename, ios::binary | ios::ate); if (!file) { cout << "Не удалось открыть файл!" << endl; return; } streamsize size = file.tellg(); file.seekg(0, ios::beg); vector<char> buffer(size); if (!file.read(buffer.data(), size)) { cout << "Ошибка чтения файла!" << endl; return; } char search[256]; cout << "Введите строку для поиска: "; cin.ignore(); cin.getline(search, sizeof(search)); size_t count = 0; char* pos = buffer.data(); while ((pos = strstr(pos, search)) != nullptr) { ++count; pos += strlen(search); } cout << "Число вхождений: " << count << endl; } int main() { setlocale(LC_ALL, "Russian"); int choice; do { cout << "Меню:\n"; cout << "1. Печать данных в шестнадцатеричном и двоичном виде\n"; cout << "2. Калькулятор побитовых операций\n"; cout << "3. Анализ памяти структуры Student\n"; cout << "4. Обработка текстового файла\n"; cout << "0. Выход\n"; cout << "Ваш выбор: "; cin >> choice; switch (choice) { case 1: { uint8_t data[16] = { 0x1F, 0x2A, 0x3C, 0x4D, 0x5E, 0x6F, 0x7B, 0x8C, 0x9D, 0xAF, 0xBA, 0xCB, 0xDC, 0xED, 0xFE, 0xFF }; cout << "Шестнадцатеричное представление:" << endl; print_in_hex(data, sizeof(data)); cout << "Двоичное представление:" << endl; print_in_binary(data, sizeof(data)); break; } case 2: bitwise_calculator(); break; case 3: analyze_student_memory(); break; case 4: file_processing(); break; case 0: cout << "Выход из программы." << endl; break; default: cout << "Неверный выбор!" << endl; } } while (choice != 0); return 0; }
Войдите, чтобы присоединиться к обсуждению.
Нет этапа
Нет проекта
Нет назначенных лиц
1 участников
Уведомления
Срок выполнения

Срок выполнения не установлен.

Зависимости

Зависимостей нет.

Reference: SemenovDK/lab04#1
Загрузка…
Пока нет содержимого.