Klim1988
25-10-2010, 12:54
Доброго время суток уважаемые форумчане, дали задание написать программу, получилось мне ее написать консольной. Помогите пожалуйста преобразовать ее из консольной в визуальную, т.е. чтобы программа работала с кнопок
вот код программы
#include "stdafx.h"
#include <string.h>
#include <conio.h>
#include <iostream>
#include<iterator>
#include <stdio.h>
char UpSymbol(char c){
int i=(int)c;
if ((i>96)&&(i<122)){
i=i-32;
};
if ((i>-97)&&(i<-80)){
i=i-32;
};
if ((i>-33)&&(i<-16)){
i=i-80;
};
if (i==-15){
i=-16;
};
return (char)i;
}
int main(void)
{
using namespace std;
char s[255];
int i;
cout<<"Enter Text: ";
cin.getline(s,255);
s[0]=UpSymbol(s[0]);
for(i=0;i<strlen(s);i++){
if (s[i]==' '){
s[i+1]=UpSymbol(s[i+1]);
}
}
cout << "Resultat: " << s << endl;
getch();
}
Само задание
Задание:
Дан текст. С помощью процедуры преобразовать первую букву каждого слова в предложении в заглавную.
надо сдать программу в среду, пожалуйста помогите...
Klim1988
26-10-2010, 13:55
Вот решение моей задачи уже визуально
#pragma once
namespace pr7 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Сводка для Form1
///
/// Внимание! При изменении имени этого класса необходимо также изменить
/// свойство имени файла ресурсов ("Resource File Name") для средства компиляции управляемого ресурса,
/// связанного со всеми файлами с расширением .resx, от которых зависит данный класс. В противном случае,
/// конструкторы не смогут правильно работать с локализованными
/// ресурсами, сопоставленными данной форме.
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: добавьте код конструктора
//
}
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
protected:
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::RichTextBox^ richTextBox1;
private: System::Windows::Forms::RichTextBox^ richTextBox2;
private: System::ComponentModel::IContainer^ components;
private:
/// <summary>
/// Требуется переменная конструктора.
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// Обязательный метод для поддержки конструктора - не изменяйте
/// содержимое данного метода при помощи редактора кода.
/// </summary>
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->button2 = (gcnew System::Windows::Forms::Button());
this->label1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox());
this->richTextBox2 = (gcnew System::Windows::Forms::RichTextBox());
this->SuspendLayout();
//
// button1
//
this->button1->Location = System::Drawing::Point(11, 267);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 2;
this->button1->Text = L"Процесс";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
//
// button2
//
this->button2->Location = System::Drawing::Point(403, 267);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(69, 25);
this->button2->TabIndex = 3;
this->button2->Text = L"Выход";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(16, 19);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(103, 13);
this->label1->TabIndex = 4;
this->label1->Text = L"Поле ввода текста";
this->label1->Click += gcnew System::EventHandler(this, &Form1::label1_Click);
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(8, 153);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(111, 13);
this->label2->TabIndex = 5;
this->label2->Text = L"Поле вывода текста";
this->label2->Click += gcnew System::EventHandler(this, &Form1::label2_Click);
//
// richTextBox1
//
this->richTextBox1->ForeColor = System::Drawing::Color::Black;
this->richTextBox1->Location = System::Drawing::Point(119, 19);
this->richTextBox1->Name = L"richTextBox1";
this->richTextBox1->Size = System::Drawing::Size(353, 111);
this->richTextBox1->TabIndex = 1;
this->richTextBox1->Text = L"";
//
// richTextBox2
//
this->richTextBox2->BackColor = System::Drawing::SystemColors::ControlLightLight;
this->richTextBox2->CausesValidation = false;
this->richTextBox2->Location = System::Drawing::Point(119, 153);
this->richTextBox2->Name = L"richTextBox2";
this->richTextBox2->Size = System::Drawing::Size(353, 111);
this->richTextBox2->TabIndex = 7;
this->richTextBox2->Text = L"";
this->richTextBox2->TextChanged += gcnew System::EventHandler(this, &Form1::richTextBox2_TextChanged);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(484, 298);
this->ControlBox = false;
this->Controls->Add(this->richTextBox2);
this->Controls->Add(this->richTextBox1);
this->Controls->Add(this->label2);
this->Controls->Add(this->label1);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->MaximizeBox = false;
this->MinimizeBox = false;
this->Name = L"Form1";
this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"Преобразование текста";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
wchar_t UpSymbol(wchar_t c){
int i=(int)c; // Если текущий символ попадает в диапозонстрочных букв,
//то переводим его в заглавную
if ((i>96)&&(i<123)){
i=i-32;
}; //Диапозон английских строчных букв
if ((i>1071)&&(i<1104)){
i=i-32;
}; // Диапозон русских строчных букв
if (i==1105){
i=1025;
}; // Буква ё
return (wchar_t)i;
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
// --------------------------------------------------------
int i, f; // i-для цикла, f=true, если пробел
String ^str1, ^str2; // str1- первоначальная строка
// str2- результирующая строка, в котторой
// все слова начинаются с заглавной буквы
// В строку str1 помещаем строку из формы
str1=richTextBox1->Text;
// 1 символ в строке делаем заглавным
str2 = String::Concat( str2, UpSymbol(str1[0]));
f=false;
for(i=1;i<str1->Length;i++){
if (str1[i]==' '){
f=true; // найден пробел, добавем его в 2 строку
str2 = String::Concat( str2, str1[i]);
};
if (str1[i]!=' '){
if (f) { // Предыдущий символ пробел
f=false;
// 1 символ слова, делаем букву заглавной и
// добавляем ее во вторую строку
str2 = String::Concat( str2, UpSymbol(str1[i]));
}
else{
// Копируем текущий символ из строки 1
// в строку 2
str2 = String::Concat( str2, str1[i]);
};
};
};
// Выводим полученную строку в форму
richTextBox2->Text=str2;
};
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
Close(); // Закрытие прокраммы
}
private: System::Void label1_Click(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void richTextBox2_TextChanged(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void label2_Click(System::Object^ sender, System::EventArgs^ e) {
}
};
}
Модуль или по-хитрому собирается, или действительно не хватает точки входа.
Если второе, то ещё нужен код [STAThreadAttribute]
int main(array<System::String ^> ^args)
{
Application::Run(gcnew Form1);
return 0;
}где здесь (/*<--->*/)
private: System::Void label2_Click(System::Object^ sender, System::EventArgs^ e) {
}
};
/*<--->*/
}
Тогда всё соберётся командой cl "Source.cpp" /clr:pure /FU "%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\System.dll" /FU "%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll" /FU "%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll" /FU "%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\System.Data.dll" /link /ENTRY:"main" /SUBSYSTEM:WINDOWS
WinForm не единственный способ визуализации в Visual C++, про другие возможности в этой теме (http://forum.oszone.net/thread-147764.html).
Про доступность этого способа, применительно к решению задания, нужно было сообщить, так как в другой теме, но применительно к этому/схожему заданию, был сказан совсем другой способ.
его нужно выполнять в среде программирования Visual C. Создавая MFC-приложение. >> (http://forum.oszone.net/post-1522296.html#post1522296)
p.s. Программа не проверяет входящие данные, при пустом "Поле для ввода текста" и нажатии кнопки "Процесс" произойдёт исключении "Index was outside the bounds of the array."
В private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) это нужно учитывать (например добавив проверку if (str1 -> Length > 0)).
vBulletin v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.