==> MainForm.cs



        // 컨트롤 - 대화상자 - 폰트
        private void miFont_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmFontDialog ffd = new MyWinForms.Controls.FrmFontDialog();
            ffd.MdiParent = this;
            ffd.Show();
        }



==============================================================================================



==> FrmFontDialog.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Controls
{
    public partial class FrmFontDialog : Form
    {
        public FrmFontDialog()
        {
            InitializeComponent();
        }

        private void btnFont_Click(object sender, EventArgs e)
        {
            // 폰트창을 열고,
            DialogResult dr =
                this.fdFont.ShowDialog();
            // 확인 버튼 누르면, 변경
            if (dr == DialogResult.OK)
            {
                txtFont.Font = fdFont.Font;
            }
        }

        private void btnColor_Click(object sender, EventArgs e)
        {
            // 색상창 열고,
            if (cdColor.ShowDialog() != DialogResult.Cancel)
            {
                txtFont.ForeColor = cdColor.Color; // 글꼴색 변경
            }
        }

    }
}



< 실행결과 >





-->"글꼴"버튼을 눌렀을 때 화면( "글꼴"창 왼쪽 아래 있는 "색"은 FrmFontDialog.cs [디자인]에서 FontDialog의 속성 중 "ShowColor -> True"로 바꿔줘야 나타난다._




--> "색상"버튼을 눌렀을 때 화면






Posted by holland14
:


==> MainForm.cs


        private void miDialogResult_Click(object sender, EventArgs e)
        {
            MyWinForms.Class.FrmDialogResult fdr = new MyWinForms.Class.FrmDialogResult();
            fdr.Show();
        }



==============================================================================================



==> FrmDialogResult.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Class
{
    public partial class FrmDialogResult : Form
    {
        public FrmDialogResult()
        {
            InitializeComponent();
        }
        // 속성
        public string Value { get; set; }
        private void btnSend_Click(object sender, EventArgs e)
        {
            // 자식 폼으로 데이터 전송
            MyWinForms.Class.FrmDialogResultChild c = new FrmDialogResultChild();
            c.Owner = this; // 자식 폼의 주인 FrmDialogResult
            c.SendValue = txtParent.Text; // 속성으로 값을 전달
            //DialogResult dr = c.ShowDialog(); // 폼 로드되면서 전송된 텍스트가 자식 폼에 출력
            if (c.ShowDialog() == DialogResult.OK)
            {
                this.txtResult.Text = Value;
            }
        }
    }
}



==============================================================================================



==> FrmDialogResultChild.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Class
{
    public partial class FrmDialogResultChild : Form
    {
        public FrmDialogResultChild()
        {
            InitializeComponent();
        }

        // 속성
        public string SendValue { get; set; }

        private void FrmDialogResultChild_Load(object sender, EventArgs e)
        {
            // 폼 로드시 SendValue 속성에 담긴 값 저장
            this.txtChild.Text = SendValue;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            FrmDialogResult fdr = (FrmDialogResult)Owner;
            fdr.Value = txtReturn.Text; // 텍스트 전송
            this.Close(); // 현재 폼 닫기
        }
    }
}



< 실행결과 >




==> FrmDialogResult(부모)에서 'abc'를 입력후 '전송'버튼을 누르면 FrmDialogResultChild(자식)에 같은값(abc)이 나옴



==> FrmDialogResultChild에서 '123'을 입력 후 '확인'버튼을 누르면 FrmDialogResultChild폼은 사라지면서 FrmDialogResult에서 '123'이 나옴



Posted by holland14
:

==> MainForm.cs



        private void miGroupBox_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmGroupBox gb = new MyWinForms.Controls.FrmGroupBox();
            gb.MdiParent = this;
            gb.Show();
        }




==============================================================================================



==> FrmGroupBox.cs [디자인]에서 폼안에 그룹박스를 2개 만들고(성별, 결혼), 각 그룹박스 안에 라디오 버튼을 2개씩 만들었다.(남자, 여자 / 미혼, 기혼)  그리고 속성에서 "성별"그룹박스의 속성은 Anchor -> Top, Right로, "결혼"그룹박스의 속성은 Dock -> Bottom으로 설정하여 그룹박스의 위치를 고정시켰다.


< 실행결과 >







Posted by holland14
:


==> MainForm.cs



        private void miComboListBox_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmComboListBox clb = new MyWinForms.Controls.FrmComboListBox();
            clb.MdiParent = this;
            clb.Show();
        }



==============================================================================================



==> FrmComboListBox.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Controls
{
    public partial class FrmComboListBox : Form
    {
        public FrmComboListBox()
        {
            InitializeComponent();
        }

        private void FrmComboListBox_Load(object sender, EventArgs e)
        {
            // 동적으로 아이콘의 종류를 리스트박스에 초기화
            lstIcon.Items.Add(MessageBoxIcon.Error.ToString());
            lstIcon.Items.Add(MessageBoxIcon.Information.ToString());
            lstIcon.Items.Add(MessageBoxIcon.Question.ToString());
            lstIcon.Items.Add(MessageBoxIcon.Warning.ToString());   
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (lstButton.SelectedIndex != -1 && lstIcon.SelectedIndex != -1)
            {
                string btn = lstButton.Items[lstButton.SelectedIndex].ToString();
                string icon = lstIcon.Items[lstIcon.SelectedIndex].ToString();

                // Process

                MessageBox.Show(
                    String.Format("버튼 : {0}, 아이콘 : {1}", btn, icon));
            }
            else
            {
                DialogResult result = MessageBox.Show(
                    "콤보박스와 리스트박스를 선택하시오."
                    ,"제목"
                    , MessageBoxButtons.OKCancel);

                if (result == DialogResult.OK)
                {
                    lblResult.Text = "확인 클릭";
                }
                else if (result == DialogResult.Cancel)
                {
                    lblResult.Text = "취소 클릭";
                }
            }
        }
    }
}



< 실행결과 >








==> 콤보박스와 리스트박스 둘 중 하나라도 선택되지 않은 후 확인버튼을 눌렀을 때 화면



==> 바로 위에서 확인 또는 취소버튼을 누르면 폼 왼쪽 아래쪽에 "확인 클릭" 또는 "취소 클릭" 텍스트가 나온다.




==> 콤보박스와 리스트박스 둘 다 선택한 후 확인버튼을 눌렀을 때의 화면






Posted by holland14
:


==> MainForm.cs



        private void miMessageBox_Click(object sender, EventArgs e)
        {
            // 메시지 박스의 주요 모양
            // MSDN 온라인 적극 활용
            // 코드조각 : mbox
            MessageBox.Show("기본");
            MessageBox.Show("캡션", "제목");
            MessageBox.Show("버튼의 종류", "버튼", MessageBoxButtons.OKCancel);
            MessageBox.Show("아이콘의 종류", "아이콘", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }



< 실행결과 >




--> 처음 실행화면 



--> 두번째 실행화면



--> 세번째 실행 화면




--> 마지막 실행화면





/*
메시지박스(MessageBox)는 컨트롤이 아닌 클래스이다. 메시지박스는 도구상자에 없음.
*/

Posted by holland14
:


==> FrmAbout.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace MyWinForms
{
    public partial class FrmAbout : Form
    {
        public FrmAbout()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            // 현재 폼 닫기
            this.Close();
        }

        private void lnkAuthor_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string url = "http://www.dotnetkorea.com/";
            System.Diagnostics.Process.Start(url); // 위 경로 띄우기

            Process.Start("notepad.exe"); // 실행 창에서 여는 명령어
            //Process.Start("mspaint"); // 그림판
            //Process.Start("inetmgr"); // IIS 웹 서버
        }
    }
}



< 실행결과 >

--> '도구상자'에서 '폼'으로 링크레이블(LinkLabel) 드래그 & 드롭





--> '작성자' 텍스트가 있는 쪽은 '레이블' / 아래 파란색 텍스트로 되어있는 부분은 '링크레이블'이다.





--> 링크 클릭 후 실행된 결과화면




Posted by holland14
:


==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}



==============================================================================================



==> MainForm.cs



        private void miTextBox_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmTextBox ftb = new MyWinForms.Controls.FrmTextBox();
            ftb.MdiParent = this;
            ftb.Show();
        }



==============================================================================================



==> FrmTextBox.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Controls
{
    public partial class FrmTextBox : Form
    {
        public FrmTextBox()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("싱글라인 : " + txtSingleLine.Text);
            sb.AppendFormat("멀티라인 : {0}", txtMultiLine.Text);
            sb.Append(String.Format("패스워드 : {0}", txtPassword.Text));
            sb.Append("마스크 : " + txtMaskedText.Text);
            sb.AppendFormat("리치 : {0}", txtRichTextBox.Text);

            MessageBox.Show(sb.ToString());
        }
    }
}



< 실행결과 >












/*
읽기전용(ReadOnly) 텍스트박스는 텍스트박스와는 달리 텍스트박스에 이미 텍스트가 입력되어 있으며, 레이블에 쓰여져 있는 텍스트와는 달리 긁어서 복사할 수 있다.
*/

Posted by holland14
:


==> MainForm.cs



        #region 컨텍스트메뉴
        private void cmsAbout_Click(object sender, EventArgs e)
        {
            //FrmAbout fa = new FrmAbout();
            //fa.ShowDialog();
            miAbout_Click(null, null); // 재 사용
        }

        private void cmsExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion

        private void miLable_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmButtonLableTextBox blt = new MyWinForms.Controls.FrmButtonLableTextBox();
            blt.MdiParent = this;
            blt.Show();
        }

        private void miCheckBoxRadioButton_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmCheckBoxRadioButton cbrb = new MyWinForms.Controls.FrmCheckBoxRadioButton();
            cbrb.MdiParent = this;
            cbrb.Show();
        }




==============================================================================================



==> FrmCheckBoxRadioButton.cs
 


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Controls
{
    public partial class FrmCheckBoxRadioButton : Form
    {
        public FrmCheckBoxRadioButton()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            string msg = "";
           
            // 관심사항
            if (this.chkSeeSharp.Checked)               //[1] 체크되었다면
            {
                msg += this.chkSeeSharp.Text + "\r\n";
            }

            if (this.chkAspNet.Checked == true)         //[2] 체크 true면
            {
                msg += this.chkAspNet.Text + "\r\n";
            }

            if (!chkSilverlight.Checked)                //[3] 체크가 되지 않았다면,
            {
                // Empty
            }
            else
            {
                msg += this.chkSilverlight.Text + "\r\n";
            }

            // 성별
            if (this.rdoMan.Checked)
            {
                msg += String.Format("{0}{1}{0}", "\r\n", rdoMan.Text);
            }
            else
            {
                msg += String.Format("{0}{1}{0}", "\r\n", optWomen.Text);
            }

            this.txtResult.Text = msg;
        }

        private void FrmCheckBoxRadioButton_Load(object sender, EventArgs e)
        {
            // 폼 로드시 동적으로 라디오버튼 체크
            this.rdoMan.Checked = true;

        }
    }
}



< 실행결과 >








==> 체크박스에 체크하고 라디오버튼에서 선택한 후 "확인"버튼을 누르면 아래 텍스트박스에서 체크한 결과가 출력됨.(여기서는 초기에 FrmCheckBoxRadioButton.cs[디자인]에서 "ASP.NET"체크박스의 속성을 Checked --> True로 해주었고, FrmCheckBoxRadioButton.cs코드에서 this.rdoMan.Checked = true;로 하여 폼 로드시 동적으로 "남자"라디오버튼이 체크되게 하였다.)




체크박스는 다중선택이 가능하지만 라디오버튼은 택1만 가능하다.

Posted by holland14
:


==> MainForm.cs



        #region 컨텍스트메뉴
        private void cmsAbout_Click(object sender, EventArgs e)
        {
            //FrmAbout fa = new FrmAbout();
            //fa.ShowDailog();
            miAbout_Click(null, null); // 재 사용
        }

        private void cmsExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion

        private void miLabel_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmButtonLaberlTextBox blt = new MyWinForms.Controls.FrmButtonLaberlTextBox();
            blt.MdiParent = this;
            blt.Show();
        }

        private void FrmCheckBoxRadioButton_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmCheckBoxRadioButton cbrb = new MyWinForms.Controls.FrmCheckBoxRadioButton();
            cbrb.MdiParent = this;
            cbrb.Show();
        }




==============================================================================================


==> FrmButtonLaberlTextBox.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Controls
{
    public partial class FrmButtonLaberlTextBox : Form
    {
        public FrmButtonLaberlTextBox()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            int kor = Convert.ToInt32(txtKor.Text);
            int eng = Int32.Parse(txtEng.Text);

            int tot = kor + eng;
           
            // mbox  ==> MessageBox의 코드조각이다. cw ==> Console.WriteLine과 같은 코드조각이다.
            MessageBox.Show(String.Format("{0} + {1} = {2}", kor, eng, tot));

            btnCancel_Click(null, null); // 재 호출
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.txtKor.Text = "";
            this.txtEng.Text = String.Empty;
            txtKor.Focus();
        }

        private void txtKor_KeyDown(object sender, KeyEventArgs e)
        {
            // 두번째 매개변수 e.KeyCode로 키보드값을 반환
            if (e.KeyCode == Keys.Enter)
            {
                this.txtEng.Focus(); // 포커스 부여
            }
        }

        private void txtEng_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btnOK_Click(null, null); // 확인 버튼 클릭
            }
        }
    }
}


< 실행결과 >








Posted by holland14
:


==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace 인터넷쇼핑몰문제
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Frm인터넷쇼핑몰());
        }
    }
}




==============================================================================================



==> OrderInfo.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 인터넷쇼핑몰문제
{
    public class OrderInfo {
        // 입력
        public int 고객회원번호 { get; set; }
        public string 주문상품코드 { get; set; }
        public int 주문수주량 { get; set; }
        // 고객회원번호=>[회원정보] 표 참조
        public int 연령 { get; set; }
        public string 성별 { get; set; }
        // 주문상품코드=>[주문상품정보] 표 참조
        public string 상품명 { get; set; }
        public int 단가 { get; set; }
    }
    public class OrderDetail {
        public string 주문상품명 { get; set; }
        public int 주문율10 { get; set; }
        public int 주문율20 { get; set; }
        public int 주문율30 { get; set; }
        public int 전체수주량 { get; set; }
        // 프로젝트 어디에서나 'OrderDetail.남자주문총금액' 으로 접근
        public static int 남자주문총금액;
        public static int 여자주문총금액;
    }
}




==============================================================================================



==> Frm인터넷쇼핑몰.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 인터넷쇼핑몰문제
{
    public partial class Frm인터넷쇼핑몰 : Form
    {
        public Frm인터넷쇼핑몰()
        {
            InitializeComponent();
            orders =  new List<OrderInfo>();
        }

        private List<OrderInfo> orders;

        private void btn입력_Click(object sender, EventArgs e)
        {
            OrderInfo oi = new OrderInfo();
            oi.고객회원번호 = Convert.ToInt32(txt고객회원번호.Text);
            oi.주문상품코드 = txt주문상품코드.Text.ToUpper(); // 대문자
            oi.주문수주량 = Convert.ToInt32(txt주문수주량.Text);

           
            //[1] 코드표 참조(회원정보 테이블/주문상품정보 테이블)
            #region 회원정보
           
            switch (oi.고객회원번호)
            {
                case 101: oi.연령 = 36; oi.성별 = "여자"; break;
                case 102: oi.연령 = 28; oi.성별 = "남자"; break;
                case 103: oi.연령 = 17; oi.성별 = "여자"; break;
                case 104: oi.연령 = 39; oi.성별 = "여자"; break;
                case 105: oi.연령 = 21; oi.성별 = "남자"; break;
                case 106: oi.연령 = 35; oi.성별 = "여자"; break;
                case 107: oi.연령 = 11; oi.성별 = "남자"; break;
                case 108: oi.연령 = 19; oi.성별 = "여자"; break;
                case 109: oi.연령 = 24; oi.성별 = "여자"; break;
                case 110: oi.연령 = 30; oi.성별 = "남자"; break;
                default: break;
            }
           
            #endregion
            #region 주문상품정보
           
            switch (oi.주문상품코드)
            {
                case "PA": oi.상품명 = "책상";     oi.단가 = 100000; break;
                case "PB": oi.상품명 = "냉장고";   oi.단가 = 360000; break;
                case "PC": oi.상품명 = "세탁기";   oi.단가 = 220000; break;
                case "PD": oi.상품명 = "VTR";       oi.단가 = 300000; break;
                case "PE": oi.상품명 = "자전거";   oi.단가 = 90000; break;
                case "PF": oi.상품명 = "시계";     oi.단가 = 6000; break;
                case "PG": oi.상품명 = "TV";       oi.단가 = 80000; break;
                case "PH": oi.상품명 = "탁자";     oi.단가 = 30000; break;
                default:
                    break;
            }
           
            #endregion

            orders.Add(oi); // 한개 레코드 저장
            txt고객회원번호.Text = txt주문상품코드.Text = txt주문수주량.Text = "";
        }

        private void btn출력_Click(object sender, EventArgs e) {
           

            //[2] Process
            List<OrderDetail> details = new List<OrderDetail>();
            OrderDetail od;
            for (int i = 0; i < orders.Count; i++) {
                od = new OrderDetail();
                od.주문상품명 = orders[i].상품명;
                od.전체수주량 = orders[i].주문수주량; // G
                switch (Convert.ToInt32(orders[i].연령 / 10)) {
                    case 1:
                        od.주문율10 = od.전체수주량; od.주문율20 = 0; od.주문율30 = 0; // G
                        break;
                    case 2:
                        od.주문율10 = 0; od.주문율20 = od.전체수주량; od.주문율30 = 0; // G
                        break;
                    case 3:
                        od.주문율10 = 0; od.주문율20 = 0; od.주문율30 = od.전체수주량; // G
                        break;
                    default:
                        break;
                }
                details.Add(od);
                // 남, 여 주문 총 금액
                if (orders[i].성별 == "남자")
                {
                    OrderDetail.남자주문총금액 +=
                        (orders[i].단가 * orders[i].주문수주량);
                }
                else
                {
                    OrderDetail.여자주문총금액 +=
                        (orders[i].단가 * orders[i].주문수주량);
                }
            }
           
            //[!] 그룹 알고리즘 적용
           
            //[A] 소트
            #region 정렬
            OrderDetail imsi = new OrderDetail();
            for (int i = 0; i < details.Count - 1; i++)
            {
                for (int j = i + 1; j < details.Count; j++)
                {
                    if (String.Compare(details[i].주문상품명, details[j].주문상품명) > 0)
                    {
                        imsi = details[i]; details[i] = details[j]; details[j] = imsi;
                    }
                }
            }
            #endregion
                       
            //[B] 그룹
            List<OrderDetail> result = new List<OrderDetail>();
            int subTotal = 0; // 소계
            int age10 = 0; int age20 = 0; int age30 = 0; // G
            for (int i = 0; i < details.Count; i++)
            {
                subTotal += details[i].전체수주량;
                age10 += details[i].주문율10; // G
                age20 += details[i].주문율20; // G
                age30 += details[i].주문율30;  // G
                if ((i + 1) == details.Count ||
                    String.Compare(details[i].주문상품명, details[i + 1].주문상품명) != 0)
                {
                    OrderDetail rlt = new OrderDetail();
                    rlt.주문상품명 = details[i].주문상품명;
                    rlt.전체수주량 = subTotal; // 현재까지 소계
                    rlt.주문율10 = age10; // G
                    rlt.주문율20 = age20; // G
                    rlt.주문율30 = age30; // G
                    result.Add(rlt); // 한개 그룹 저장
                    subTotal = 0; age10 = 0; age20 = 0; age30 = 0; // G
                }
            }
           
            // 연령별 주문율 계산
            for (int i = 0; i < result.Count; i++) // G
            {
                if (result[i].주문율10 > 0)
                    result[i].주문율10 = Convert.ToInt32((result[i].주문율10 / (double)result[i].전체수주량) * 100);
                if (result[i].주문율20 > 0)
                    result[i].주문율20 = Convert.ToInt32((result[i].주문율20 / (double)result[i].전체수주량) * 100);
                if (result[i].주문율30 > 0)
                    result[i].주문율30 = Convert.ToInt32((result[i].주문율30 / (double)result[i].전체수주량) * 100);
            }
           
           
           
            //[3] Output
            lbl남.Text +=
                String.Format("{0:###,###}", OrderDetail.남자주문총금액);
            lbl여.Text +=
                String.Format("{0:###,###}", OrderDetail.여자주문총금액);
            this.ctlPrint.DataSource = result; // 일단 출력
        }
    }
}




< 실행결과 >









* 참고자료 --> C++로 구현한 코드




#include <iostream>
#include <fstream>
#include <string>

using namespace std;

const int MAX = 80;

// 3개의 값 입력 자료 : 파일에서 읽어오기
struct Member
{
    int Num;            // 번호
    int Age;            // 나이
    char Gender;        // 성별
};

// 입력 자료 저장 구조체
struct InData
{
    int Num;            // 번호
    int Age;            // 나이
    char Gender;        // 성별

    char Code[3];       // 코드
    int Order;          // 수주량
    char Name[25];      // 상품명
    int Ten;            // 10대
    int Twenty;         // 20대
    int Thirty;         // 30대
    int Total;          // 전체수주량
    int Cost;           // 단가
};

// 출력 자료 저장
struct OutData
{
    char Name[25];      // 상품명
    int Ten;            // 10대 주문률
    int Twenty;         // 20대
    int Thirty;         // 30대
    int Total;          // 총
    int Order;          // 단가
};

// 10개 데이터 입출력 저장 구조체 배열 선언
static struct InData inData[10];    // 회원정보 10명
static struct OutData procData[10]; // Process 임시 처리
static struct OutData outData[10];  // 출력

void main(void)
{
    //[!] 멤버 정보 읽어오기 start
    static struct Member member[10];
    //[1] 파일 읽기 개체 생성
    ifstream in;
    //[2] 파일 오픈
    in.open("C:\\Temp\\InShop.txt");
    //[3] 전체 읽어 오기
    char oneline[MAX];
    int count = 0;
    while (in.getline(oneline, MAX))
    {
        string data = oneline;
        member[count].Num = atoi(data.substr(0, 3).c_str());
        member[count].Age = atoi(data.substr(3, 3).c_str());
        if (strcmp(data.substr(7).c_str(), "남자") == 0)
        {
            member[count].Gender = 'M';
        }
        else
        {
            member[count].Gender = 'F';
        }

        count++;
    }
    //[4] 닫기
    in.close();
    //[!] 멤버 정보 읽어오기 end


    //[!] 화면으로부터 3개의 데이터 읽어서 inData[] 구조체 배열에 저장
    int cnt = 0;
    char buff[100];
    char c[2];
    do
    {
        cout << "고객회원번호 : "; cin >> inData[cnt].Num;
        cout << "주문상품코드 : "; cin >> buff; strcpy(inData[cnt].Code, buff);
        cout << "주문량 : "; cin >> inData[cnt].Order;
        cout << "계속(y) 중지(n)"; cin >> c;
        cnt++;
    } while (c[0] == 'y');

    // 입력 데이터 출력
    for (int i = 0; i < cnt; i++)
    {
        cout << inData[i].Num << ", " << inData[i].Code << ", " << inData[i].Order << endl;
    }


    long manTotal = 0;      // 남자 주문 총금액
    long womenTotal = 0;    // 여자 주문 총금액
    for (int i = 0; i < cnt; i++)
    {
        //inData[i].Ten = inData[i].Twenty = inData[i].Thirty = inData[i].Total; // 초기화
        for (int j = 0; j < 10; j++)
        {
            if (inData[i].Num == member[j].Num)
            {
                inData[i].Age = member[j].Age;
                inData[i].Gender = member[j].Gender;

                if (inData[i].Age <= 19)
                {
                    inData[i].Ten = inData[i].Order;
                }
                else if (inData[i].Age >= 20 && inData[i].Age <= 29)
                {
                    inData[i].Twenty = inData[i].Order;                
                }
                else if (inData[i].Age >= 30 && inData[i].Age <= 39)
                {
                    inData[i].Thirty = inData[i].Order;                                
                }

                inData[i].Total = inData[i].Ten + inData[i].Twenty + inData[i].Thirty;

                //[!] 주문상품정보
                switch(inData[i].Code[1])
                {
                case 'A':
                    strcpy(inData[i].Name, "책상");
                    inData[i].Cost = 100000;
                    break;
                case 'B':
                    strcpy(inData[i].Name, "냉장고");
                    inData[i].Cost = 360000;
                    break;
                case 'C':
                    strcpy(inData[i].Name, "세탁기");
                    inData[i].Cost = 220000;
                    break;
                case 'D':
                    strcpy(inData[i].Name, "VTR");
                    inData[i].Cost = 300000;
                    break;
                case 'E':
                    strcpy(inData[i].Name, "자전거");
                    inData[i].Cost = 90000;
                    break;
                case 'F':
                    strcpy(inData[i].Name, "시계");
                    inData[i].Cost = 6000;
                    break;
                case 'G':
                    strcpy(inData[i].Name, "TV");
                    inData[i].Cost = 80000;
                    break;
                case 'H':
                    strcpy(inData[i].Name, "탁자");
                    inData[i].Cost = 30000;
                    break;
                }
            }
        }

        // 남/여 주문 총금액
        if (inData[i].Gender == 'M')
        {
            manTotal += (inData[i].Order * inData[i].Cost);
        }
        else
        {
            womenTotal += (inData[i].Order * inData[i].Cost);
        }
    }

 

    // 처리
    // 대입 : procData에서 정렬 및 그룹알고리즘 적용
    for (int i = 0; i < cnt; i++)
    {
        strcpy(procData[i].Name, inData[i].Name);
        procData[i].Ten = inData[i].Ten;
        procData[i].Twenty = inData[i].Twenty;
        procData[i].Thirty = inData[i].Thirty;
        procData[i].Total = inData[i].Total;
        procData[i].Order = inData[i].Order;
    }

    // 입력 데이터 출력
    for (int i = 0; i < cnt; i++)
    {
        cout << procData[i].Ten << ", " << procData[i].Twenty << ", " << procData[i].Thirty << endl;
    }

    //[A] 정렬(선택) : 상품명에 따라서 정렬
    struct OutData temp;
 for (int i = 0; i < cnt - 1; i++)
 {
  for (int j = i + 1; j < cnt; j++)
  {
   if (strcmp(procData[i].Name, procData[j].Name) > 0)
   {
    temp = procData[i];
    procData[i] = procData[j];
    procData[j] = temp;
   }
  }
 }
 //[B] Group
    int ten = 0; int twenty = 0; int thirty = 0; int total = 0;
 int orderTotal = 0;  // 그룹소계
 int groupCount = 0;  // 그룹수
 for (int i = 0; i < cnt; i++)
 {
        ten += procData[i].Ten;
        twenty += procData[i].Twenty;
        thirty += procData[i].Thirty;
        total += procData[i].Total;
        orderTotal += procData[i].Order; // 그룹소계
        // 상품명이 다르면, 새로운 상품명으로 이동
  if(strcmp(procData[i].Name, procData[i+1].Name) != 0)
  {
   strcpy(outData[groupCount].Name, procData[i].Name);
            outData[groupCount].Ten = ten; // 그룹소계
            outData[groupCount].Twenty = twenty; // 그룹소계
            outData[groupCount].Thirty = thirty; // 그룹소계
            outData[groupCount].Total = total; // 그룹소계
            outData[groupCount].Order = orderTotal; // 그룹소계
   groupCount++;  // 그룹수 증가
            ten = twenty = thirty = total = orderTotal = 0; // 소계 초기화
  }
 }
    //[C] 주문률
    for (int i = 0; i < groupCount; i++)
    {
        if (outData[i].Ten > 0)
            outData[i].Ten = (double)(outData[i].Ten / (double)outData[i].Total) * 100;
        if (outData[i].Twenty > 0)
            outData[i].Twenty = (double)(outData[i].Twenty / (double)outData[i].Total) * 100;
        if (outData[i].Thirty > 0)
            outData[i].Thirty = (double)(outData[i].Thirty / (double)outData[i].Total) * 100;
    }

    // 출력 데이터 출력
    for (int i = 0; i < groupCount; i++)
    {
        cout << outData[i].Name << ", " << outData[i].Ten << ", " << outData[i].Twenty << ", " << outData[i].Thirty << ", " << outData[i].Order << endl;
    }

    cout << "주문 총 금액 : " << endl;
    cout << " 남 : " << manTotal << endl;
    cout << " 여 : " << womenTotal << endl;
}



Posted by holland14
: