4 Текст программы
Текст программы выглядит следующим образом:
//Функция проверки введено ли поле
int checkfield(System::Windows::Forms::TextBox^ txt, System::String^ message)
{
if (txt->Text == "") {
MessageBox::Show(message, "mass", MessageBoxButtons::OK,
MessageBoxIcon::Warning);
return 1;
}
return 0;
}
//Функция вывода числового массива в textBox
void arrayToString(array<int>^ arr)
{
int amount = arr->Length;
array<String^>^ mas = gcnew array<String^>(amount);
for (int i = 0; i < amount; i++) {
mas[i] += arr[i].ToString();
}
if (radButEven->Checked) {
txtRes->Text = "Чётные элементы: " + String::Join(" ", mas);
}
if (radButOdd->Checked) {
txtRes->Text = "Нечётные элементы: " + String::Join(" ", mas);
}
if (radButSortInc->Checked) {
txtRes->Text = "Сортировка по возрастанию: " + String::Join(" ", mas);
}
if (radButSortDecr->Checked) {
txtRes->Text = "Сортировка по убыванию: " + String::Join(" ", mas);
}
}
//Функция сортировки массива
void sort(array<int>^ arr, int amount, bool decr) {
array<int>^ sorted = gcnew array<int>(amount);
for (int i = 0; i < amount - 1; i++) {
int xn = arr[i];
int m = i;
for (int j = i + 1; j < amount; j++) {
if (arr[j] > xn && decr) {
xn = arr[j];
m = j;
}
else if (arr[j] < xn && decr == false) {
xn = arr[j];
m = j;
}
}
arr[m] = arr[i];
arr[i] = xn;
}
arrayToString(arr);
}
private: String^ removeExtraChars(String^ str) {
// Преобразуем String^ в std::string
std::string stdStr = marshal_as<std::string>(str->Trim());
// Удаляем лишние символы
std::string result;
wchar_t current;
wchar_t next;
for (size_t i = 0; i < stdStr.length() - 1; i++) {
current = stdStr[i];
next = stdStr[i + 1];
if (Char::IsDigit(current) ||
current == ' ' && Char::IsDigit(next)) {
result += stdStr[i];
}
if (current == '-' && Char::IsDigit(next)) {
result += ' ';
result += stdStr[i];
}
}
wchar_t last = stdStr[stdStr.length() - 1];
if (last != '-') {
result += last;
}
// Преобразуем обратно в String^
String^ resultString = gcnew String(result.c_str());
return resultString->Trim();
}
//Сгенерировать массив
private: System::Void btnGenerate_Click(System::Object^ sender, System::EventArgs^
e) {
int amount, min, max;
int hasError = 0;
hasError += checkfield(txtAmount, "Введите количество элементов для
генерации!");
hasError += checkfield(txtMin, "Введите минимальное значение диапазона!");
hasError += checkfield(txtMax, "Введите максимальное значение диапазона!");
if (hasError == 0) {
amount = Convert::ToInt32(txtAmount->Text);
min = Convert::ToInt32(txtMin->Text);
max = Convert::ToInt32(txtMax->Text);
array<String^>^ mas = gcnew array<String^>(amount);
Random^ rnd = gcnew Random;
if (min > max) { //если min > max просто меняем их местами
txtMax->Text = Convert::ToString(min);
txtMin->Text = Convert::ToString(max);
for (int i = 0; i < amount; i++) {
mas[i] = Convert::ToString(rnd->Next(max, min + 1));
}
}
else {
for (int i = 0; i < amount; i++) {
mas[i] = Convert::ToString(rnd->Next(min, max + 1));
}
}
txtMass->Text = String::Join(" ", mas);
}
}
private: System::Void btnDo_Click(System::Object^ sender, System::EventArgs^ e) {
txtMass->Text = removeExtraChars(txtMass->Text);
int hasError = 0;
hasError += checkfield(txtMass, "Исходный массив пустой!");
if (hasError == 0) {
String^ text = txtMass->Text;
array<System::String^>^ strNumbers = text->Split(' ');
int amount = strNumbers->Length;
array<int>^ numbers = gcnew array<int>(amount);
for (int i = 0; i < amount; i++)
{
numbers[i] = Convert::ToInt32(strNumbers[i]);
}
if (radButSumm->Checked) {
int sum = 0;
for (int i = 0; i < amount; i++) {
sum += numbers[i];
}
txtRes->Text = "Сумма элементов: " + Convert::ToString(sum);
}
if (radButMid->Checked) {
int sum = 0;
for (int i = 0; i < amount; i++) {
sum += numbers[i];
}
txtRes->Text = "Среднее значение элементов: " +
Convert::ToString(sum / amount);
}
if (radButMin->Checked) {
int min = numbers[0];
for (int i = 0; i < amount; i++) {
if (min > numbers[i]) {
min = numbers[i];
}
}
txtRes->Text = "Минимальный элемент: " + Convert::ToString(min);
}
if (radButMax->Checked) {
int max = numbers[0];
for (int i = 0; i < amount; i++) {
if (max < numbers[i]) {
max = numbers[i];
}
}
txtRes->Text = "Максимальный элемент: " +
Convert::ToString(max);
}
if (radButEven->Checked) {
int size = 0;
for (int i = 0; i < amount; i++) {
if (numbers[i] % 2 == 0){
size++;
}
}
array<int>^ evenarray = gcnew array<int>(size);
int j = 0;
for (int i = 0; i < amount; i++) {
if (numbers[i] % 2 == 0) {
evenarray[j] = numbers[i];
j++;
}
}
arrayToString(evenarray);
}
if (radButOdd->Checked) {
int size = 0;
for (int i = 0; i < amount; i++) {
if (numbers[i] % 2 == 1) {
size++;
}
}
array<int>^ oddarray = gcnew array<int>(size);
int j = 0;
for (int i = 0; i < amount; i++) {
if (numbers[i] % 2 == 1) {
oddarray[j] = numbers[i];
j++;
}
}
arrayToString(oddarray);
}
if (radButSortInc->Checked) {
sort(numbers, amount, 0);
}
if (radButSortDecr->Checked) {
sort(numbers, amount, 1);
}
}
}
//Ввод из файла
private: System::Void btnInput_Click(System::Object^ sender, System::EventArgs^ e) {
OpenFileDialog^ openFileDialog = gcnew OpenFileDialog;
openFileDialog->Title = "Открытие входного файла";
openFileDialog->InitialDirectory = "d:\\";
openFileDialog->Filter = "Текстовые файлы (*.txt)|*.txt";
openFileDialog->FilterIndex = 1;
openFileDialog->ShowReadOnly = true;
openFileDialog->ReadOnlyChecked = true;
openFileDialog->RestoreDirectory = true;
if (!IO::File::Exists(txtInput->Text) && openFileDialog->ShowDialog() ==
System::Windows::Forms::DialogResult::OK) {
txtInput->Text = openFileDialog->FileName;
}
if (IO::File::Exists(txtInput->Text)) {
openFileDialog->FileName = txtInput->Text;
System::IO::Stream^ fileStream = openFileDialog->OpenFile();
System::IO::StreamReader^ reader = gcnew
System::IO::StreamReader(fileStream);
String^ strArray = reader->ReadToEnd();
reader->Close();
fileStream->Close();
delete reader;
txtMass->Text = removeExtraChars(strArray);
}
}
//Вывод в файл
private: System::Void btnSave_Click(System::Object^ sender, System::EventArgs^ e) {
// Создаем диалог для сохранения файла
System::Windows::Forms::SaveFileDialog^ saveFileDialog = gcnew
System::Windows::Forms::SaveFileDialog();
saveFileDialog->Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog->Title = "Сохранить файл как";
int hasError = 0;
hasError += checkfield(txtMass, "Исходный массив пустой!");
if (hasError == 0)
{
if (!IO::File::Exists(txtOutput->Text) && saveFileDialog->ShowDialog()
== System::Windows::Forms::DialogResult::OK) {
txtOutput->Text = saveFileDialog->FileName;
}
if (IO::File::Exists(txtOutput->Text)) {
this->btnDo_Click(sender, e);
String^ saveText = "Исходный массив: " + txtMass->Text + "\n" +
txtRes->Text + "\n\n";
IO::File::AppendAllText(txtOutput->Text, saveText);
}
}
}
private: System::Void btnClose_Click(System::Object^ sender, System::EventArgs^ e) {
this->Close();
}
private: System::Void txtMass_KeyPress(System::Object^ sender,
System::Windows::Forms::KeyPressEventArgs^ e) {
if (!Char::IsDigit(e->KeyChar) && e->KeyChar != '-' && e->KeyChar != ' ' &&
e->KeyChar != '\b')
{
e->Handled = true;
}
}
private: System::Void txtAmount_KeyPress(System::Object^ sender,
System::Windows::Forms::KeyPressEventArgs^ e) {
if (!Char::IsDigit(e->KeyChar) && e->KeyChar != ' ' && e->KeyChar != '\b')
{
e->Handled = true;
}
}
private: System::Void txtMin_KeyPress(System::Object^ sender,
System::Windows::Forms::KeyPressEventArgs^ e) {
if (!Char::IsDigit(e->KeyChar) && e->KeyChar != '-' && e->KeyChar != ' ' &&
e->KeyChar != '\b')
{
e->Handled = true;
}
}
private: System::Void txtMax_KeyPress(System::Object^ sender,
System::Windows::Forms::KeyPressEventArgs^ e) {
if (!Char::IsDigit(e->KeyChar) && e->KeyChar != '-' && e->KeyChar != ' ' &&
e->KeyChar != '\b')
{
e->Handled = true;
}
}
};
}
