С Новым годом! Форум программистов, компьютерный форум, киберфорум
Visual C++
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.82/11: Рейтинг темы: голосов - 11, средняя оценка - 4.82
0 / 0 / 0
Регистрация: 06.01.2017
Сообщений: 8

Чтение из файла в строку (в MFC)

16.04.2017, 15:11. Показов 2144. Ответов 11
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Всем привет!
Есть две строки, в которые вводятся значения (два числа которые надо сложить) и текстовый документ, в котором эти значения записаны. Как мне сделать так, что бы нажатием кнопки я выбрал бы файл и в строках бы появились значения?
Миниатюры
Чтение из файла в строку (в MFC)  
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
16.04.2017, 15:11
Ответы с готовыми решениями:

Чтение файла в MFC
Есть текстовый файл TConfiguration.txt. В нем следующая информация UID=2806FA4F01000066=1 UID=28AA2A50010000BB=2 Обратите...

Чтение из файла MFC
Ребят, пишу на с++ с использованием MFC. Читаю из файла с помощью CStdioFile. Строку записываю TCHAR. Проблема в том,что вместо русских...

Чтение бинарного файла в MFC
Доброго времени суток всем! Подскажите, что-то впадаю в ступор. Есть бинарный файл: Задача, найти байты 0хЕ3 и выполнить...

11
38 / 38 / 11
Регистрация: 27.09.2014
Сообщений: 491
16.04.2017, 16:26
Цитата Сообщение от Alex12122 Посмотреть сообщение
я выбрал бы файл
CFileDialog?
Цитата Сообщение от Alex12122 Посмотреть сообщение
в строках бы появились значения
потом считываете из выбранного файла и добавляете в в нужные поля...
0
0 / 0 / 0
Регистрация: 06.01.2017
Сообщений: 8
16.04.2017, 22:41  [ТС]
мне бы сам код.. просто не очень шарю в этом пока что=)
0
38 / 38 / 11
Регистрация: 27.09.2014
Сообщений: 491
17.04.2017, 10:29
http://www.firststeps.ru/mfc/s... elp20.html
0
Заблокирован
17.04.2017, 19:47
Я не стал "сильно" парсить т.е. осуществлять всевозможные проверочные комбинации входящего файла.
Alex12122Dlg.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// Alex12122Dlg.cpp : implementation file
//
 
#include "stdafx.h"
#include "Alex12122.h"
#include "Alex12122Dlg.h"
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
/////////////////////////////////////////////////////////////////////////////
// CAlex12122Dlg dialog
 
CAlex12122Dlg::CAlex12122Dlg(CWnd* pParent /*=NULL*/)
    : CDialog(CAlex12122Dlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CAlex12122Dlg)
        // NOTE: the ClassWizard will add member initialization here
    //}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
 
    m_strTxtFile    = "";
    m_strNum1       = "";
    m_strNum2       = "";
}
 
void CAlex12122Dlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CAlex12122Dlg)
        // NOTE: the ClassWizard will add DDX and DDV calls here
    //}}AFX_DATA_MAP
 
    DDX_Text(pDX, IDC_EDIT2, m_strNum1);
    if( pDX->m_bSaveAndValidate )
    {
        if( m_strNum1.IsEmpty() )
        {
            AfxMessageBox("Пожалуйста, введите значение.", MB_OK | MB_ICONEXCLAMATION);
            pDX->PrepareEditCtrl(IDC_EDIT2);
            pDX->Fail();
        }
    }
 
    DDX_Text(pDX, IDC_EDIT3, m_strNum2);
    if( pDX->m_bSaveAndValidate )
    {
        if( m_strNum2.IsEmpty() )
        {
            AfxMessageBox("Пожалуйста, введите значение.", MB_OK | MB_ICONEXCLAMATION);
            pDX->PrepareEditCtrl(IDC_EDIT3);
            pDX->Fail();
        }
    }
}
 
BEGIN_MESSAGE_MAP(CAlex12122Dlg, CDialog)
    //{{AFX_MSG_MAP(CAlex12122Dlg)
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    //}}AFX_MSG_MAP
    ON_EN_CHANGE(IDC_EDIT1, OnChangeEdit1)
    ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
    ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
    ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
END_MESSAGE_MAP()
 
void CAlex12122Dlg::OnChangeEdit1() 
{
    CEdit* pEdt=(CEdit*)GetDlgItem(IDC_EDIT1);
    if( pEdt )
    {
        pEdt->GetWindowText(m_strTxtFile);      
        
        BOOL bMode;
        if( m_strTxtFile.IsEmpty() )
            bMode = FALSE;
        else
            bMode = TRUE;
 
        CButton* pBt=(CButton*)GetDlgItem(IDC_BUTTON2);
        if( pBt ) pBt->EnableWindow(bMode);
    }
}
 
void CAlex12122Dlg::OnButton1()
{
    CFileDialog cfd(TRUE, ".txt", m_strTxtFile,
        OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY,
        "Текстовые документы (*.txt)|*.txt||");
    if( IDOK == cfd.DoModal() )
    {
        m_strTxtFile = cfd.GetPathName();
        CEdit* pEdt=(CEdit*)GetDlgItem(IDC_EDIT1);
        if( pEdt ) pEdt->SetWindowText(m_strTxtFile);
    }
}
 
//
// Incoming text file format: "1997 2017", "1997, 2017" or "23,500"
//
void CAlex12122Dlg::OnButton2()
{
    if( m_strTxtFile.IsEmpty() ) return;
    
    CStdioFile f;
    if( !f.Open(m_strTxtFile, CFile::modeRead) )
    {
        CString strError;
        strError.Format("Не удалось открыть файл\n'%s'", m_strTxtFile);
        AfxMessageBox(strError, MB_OK | MB_ICONEXCLAMATION);
        return;
    }
 
    BOOL bDone, bFound;
    bDone = bFound = FALSE;
 
    while( !bDone )
    {
        CString strLine;
        f.ReadString(strLine);
        
        for( int i=0; i < strLine.GetLength(); ++i )
        {
            if( bFound )
            {
                if( "," != strLine.Mid(i, 1) ||
                    " " != strLine.Mid(i, 1) )
                    m_strNum2 += strLine.Mid(i, 1);
            }
            else
            {
                if( "," == strLine.Mid(i, 1) ||
                    " " == strLine.Mid(i, 1) )
                    bFound = TRUE;
                else
                    m_strNum1 += strLine.Mid(i, 1);
            }
        }
        bDone = TRUE;
    }
    f.Close();
 
    SendDlgItemMessage(IDC_EDIT2, WM_SETTEXT, (WPARAM)0,
        (LPARAM)m_strNum1.operator LPCTSTR());
    SendDlgItemMessage(IDC_EDIT3, WM_SETTEXT, (WPARAM)0,
        (LPARAM)m_strNum2.operator LPCTSTR());
}
 
void CAlex12122Dlg::OnButton3()
{
    if( UpdateData(TRUE) )
    {
        CEdit* pEdt=(CEdit*)GetDlgItem(IDC_EDIT4);
        if( pEdt )
        {
            CString str;
            str.Format("%d", ( atoi(m_strNum1) + atoi(m_strNum2) ) );       
            pEdt->SetWindowText(str);
        }
    }
}
 
/////////////////////////////////////////////////////////////////////////////
// CAlex12122Dlg message handlers
 
BOOL CAlex12122Dlg::OnInitDialog()
{
    CDialog::OnInitDialog();
 
    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon
    
    // TODO: Add extra initialization here
    
    return TRUE;  // return TRUE  unless you set the focus to a control
}
 
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.
 
void CAlex12122Dlg::OnPaint() 
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting
 
        SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
 
        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
 
        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}
 
// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CAlex12122Dlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}

проект
1
0 / 0 / 0
Регистрация: 06.01.2017
Сообщений: 8
18.04.2017, 00:25  [ТС]
Дружище, спасибо тебе огромное!
0
Заблокирован
18.04.2017, 11:19
Ошибка вкралась. Строки прибавляются и прибавляются, нужно очистку производить.
OnButton2()
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//
// Incoming text file format: "1997 2017", "1997, 2017" or "23,500"
//
void CAlex12122Dlg::OnButton2()
{
    if( m_strTxtFile.IsEmpty() ) return;
    
    CStdioFile f;
    if( !f.Open(m_strTxtFile, CFile::modeRead) )
    {
        CString strError;
        strError.Format("Не удалось открыть файл\n'%s'", m_strTxtFile);
        AfxMessageBox(strError, MB_OK | MB_ICONEXCLAMATION);
        return;
    }
 
 
    /*-----------------------------------------------------------------------------
        Произвести очистку, если строки не пустые.
    -----------------------------------------------------------------------------*/
    if( !m_strNum1.IsEmpty() || !m_strNum2.IsEmpty() )
    {
        m_strNum1.Empty();
        m_strNum2.Empty();
    }
 
 
    BOOL bDone, bFound;
    bDone = bFound = FALSE;
 
    while( !bDone )
    {
        CString strLine;
        f.ReadString(strLine);
        
        for( int i=0; i < strLine.GetLength(); ++i )
        {
            if( bFound )
            {
                if( "," != strLine.Mid(i, 1) ||
                    " " != strLine.Mid(i, 1) )
                    m_strNum2 += strLine.Mid(i, 1);
            }
            else
            {
                if( "," == strLine.Mid(i, 1) ||
                    " " == strLine.Mid(i, 1) )
                    bFound = TRUE;
                else
                    m_strNum1 += strLine.Mid(i, 1);
            }
        }
        bDone = TRUE;
    }
    f.Close();
 
    SendDlgItemMessage(IDC_EDIT2, WM_SETTEXT, (WPARAM)0,
        (LPARAM)m_strNum1.operator LPCTSTR());
    SendDlgItemMessage(IDC_EDIT3, WM_SETTEXT, (WPARAM)0,
        (LPARAM)m_strNum2.operator LPCTSTR());
}
0
0 / 0 / 0
Регистрация: 24.04.2017
Сообщений: 5
29.04.2017, 18:29
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
void CAlex12122Dlg::OnButton2()
{
if( m_strTxtFile.IsEmpty() ) return;
 
CStdioFile f;
if( !f.Open(m_strTxtFile, CFile::modeRead) )
{
CString strError;
strError.Format("Не удалось открыть файл\n'%s'", m_strTxtFile);
AfxMessageBox(strError, MB_OK | MB_ICONEXCLAMATION);
return;
}
 
 
/*-----------------------------------------------------------------------------
Произвести очистку, если строки не пустые.
-----------------------------------------------------------------------------*/
if( !m_strNum1.IsEmpty() || !m_strNum2.IsEmpty() )
{
m_strNum1.Empty();
m_strNum2.Empty();
}
 
 
BOOL bDone, bFound;
bDone = bFound = FALSE;
 
while( !bDone )
{
CString strLine;
f.ReadString(strLine);
 
for( int i=0; i < strLine.GetLength(); ++i )
{
if( bFound )
{
if( "," != strLine.Mid(i, 1) ||
" " != strLine.Mid(i, 1) )
m_strNum2 += strLine.Mid(i, 1);
}
else
{
if( "," == strLine.Mid(i, 1) ||
" " == strLine.Mid(i, 1) )
bFound = TRUE;
else
m_strNum1 += strLine.Mid(i, 1);
}
}
bDone = TRUE;
}
f.Close();
 
SendDlgItemMessage(IDC_EDIT2, WM_SETTEXT, (WPARAM)0,
(LPARAM)m_strNum1.operator LPCTSTR());
SendDlgItemMessage(IDC_EDIT3, WM_SETTEXT, (WPARAM)0,
(LPARAM)m_strNum2.operator LPCTSTR());
}


Ребят, я более-менее понял как загружать 2 значения из файла таким способом, но как быть если значения 4 и все в разных строках? Что-то совсем не выходит((
0
Заблокирован
30.04.2017, 00:11
v.02
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Alex12122Dlg.cpp : implementation file
//
// v.02
//
// mabe by stamp :-_)
//
 
#include "stdafx.h"
#include "Alex12122.h"
#include "Alex12122Dlg.h"
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
/////////////////////////////////////////////////////////////////////////////
// CAlex12122Dlg dialog
 
CAlex12122Dlg::CAlex12122Dlg(CWnd* pParent /*=NULL*/)
    : CDialog(CAlex12122Dlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CAlex12122Dlg)
        // NOTE: the ClassWizard will add member initialization here
    //}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
 
    m_strTxtFile    = "";
    m_strNum1       = "";
    m_strNum2       = "";
}
 
void CAlex12122Dlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CAlex12122Dlg)
        // NOTE: the ClassWizard will add DDX and DDV calls here
    //}}AFX_DATA_MAP
 
 
    DDX_Text(pDX, IDC_COMBO1, m_strNum1);
    if( pDX->m_bSaveAndValidate )
    {
        if( m_strNum1.IsEmpty() )
        {
            AfxMessageBox("Пожалуйста, введите значение.", MB_OK | MB_ICONEXCLAMATION);
            pDX->PrepareCtrl(IDC_COMBO1);
            pDX->Fail();
        }
    }
 
    DDX_Text(pDX, IDC_COMBO2, m_strNum2);
    if( pDX->m_bSaveAndValidate )
    {
        if( m_strNum2.IsEmpty() )
        {
            AfxMessageBox("Пожалуйста, введите значение.", MB_OK | MB_ICONEXCLAMATION);
            pDX->PrepareCtrl(IDC_COMBO2);
            pDX->Fail();
        }
    }
}
 
BEGIN_MESSAGE_MAP(CAlex12122Dlg, CDialog)
    //{{AFX_MSG_MAP(CAlex12122Dlg)
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    //}}AFX_MSG_MAP
    ON_CBN_EDITCHANGE(IDC_COMBO1, OnCombo1)
    ON_CBN_EDITCHANGE(IDC_COMBO2, OnCombo2)
    ON_EN_CHANGE(IDC_EDIT1, OnChangeEdit1)
    ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
    ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
    ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
END_MESSAGE_MAP()
 
void CAlex12122Dlg::OnCombo1() 
{
    CComboBox* ccb;
    ccb=(CComboBox*)GetDlgItem(IDC_COMBO1);
    if( ccb )
        ccb->GetWindowText(m_strNum1);
}
 
void CAlex12122Dlg::OnCombo2() 
{
    CComboBox* ccb;
    ccb=(CComboBox*)GetDlgItem(IDC_COMBO2);
    if( ccb )
        ccb->GetWindowText(m_strNum2);
}
 
void CAlex12122Dlg::OnChangeEdit1() 
{
    CEdit* pEdt=(CEdit*)GetDlgItem(IDC_EDIT1);
    if( pEdt )
    {
        pEdt->GetWindowText(m_strTxtFile);      
        
        BOOL bMode;
        if( m_strTxtFile.IsEmpty() )
            bMode = FALSE;
        else
            bMode = TRUE;
 
        CButton* pBt=(CButton*)GetDlgItem(IDC_BUTTON2);
        if( pBt ) pBt->EnableWindow(bMode);
    }
}
 
void CAlex12122Dlg::OnButton1()
{
    CFileDialog cfd(TRUE, ".txt", m_strTxtFile,
        OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY,
        "Текстовые документы (*.txt)|*.txt||");
    if( IDOK == cfd.DoModal() )
    {
        m_strTxtFile = cfd.GetPathName();
        CEdit* pEdt=(CEdit*)GetDlgItem(IDC_EDIT1);
        if( pEdt ) pEdt->SetWindowText(m_strTxtFile);
    }
}
 
void CAlex12122Dlg::OnButton2()
{
    if( m_strTxtFile.IsEmpty() ) return;
    
    CStdioFile f;
    if( !f.Open(m_strTxtFile, CFile::modeRead) )
    {
        CString strError;
        strError.Format("Не удалось открыть файл\n'%s'", m_strTxtFile);
        AfxMessageBox(strError, MB_OK | MB_ICONEXCLAMATION);
        return;
    }
 
    // Clear combobox.
    SendDlgItemMessage(IDC_COMBO1, CB_RESETCONTENT, (WPARAM)0, (LPARAM)0);
    SendDlgItemMessage(IDC_COMBO2, CB_RESETCONTENT, (WPARAM)0, (LPARAM)0);
 
    int nCount = 0; // Total line.
 
    BOOL bFound = FALSE;
    CString str, strLine;
 
    while( f.ReadString(strLine) )
    {
        for( int i=0; i<strLine.GetLength(); ++i )
        {
            if( bFound )
            {
                if( "," != strLine.Mid(i, 1) ||
                    " " != strLine.Mid(i, 1) )
                    str += strLine.Mid(i, 1);
            }
            else
            {
                if( "," == strLine.Mid(i, 1) ||
                    " " == strLine.Mid(i, 1) )
                {
                    SendDlgItemMessage(IDC_COMBO1, CB_ADDSTRING, 0,
                        (LPARAM)str.operator LPCTSTR());
                    str.Empty();
                    bFound = TRUE;
                }
                else
                    str += strLine.Mid(i, 1);
            }
        }
 
        if( " " == str.Left(1) )
            str.Replace(" ",  ""); 
 
        SendDlgItemMessage(IDC_COMBO2, CB_ADDSTRING, 0,
            (LPARAM)str.operator LPCTSTR());
 
        str.Empty();
        bFound = FALSE;
 
        ++nCount;
    }
    f.Close();
    
    SendDlgItemMessage(IDC_COMBO1, CB_SETCURSEL, (WPARAM)0, (LPARAM)0);
    SendDlgItemMessage(IDC_COMBO2, CB_SETCURSEL, (WPARAM)0, (LPARAM)0);
}
 
void CAlex12122Dlg::OnButton3()
{
    if( UpdateData(TRUE) )
    {
        CEdit* pEdt=(CEdit*)GetDlgItem(IDC_EDIT4);
        if( pEdt )
        {
            CString str;
            str.Format("%d", ( atoi(m_strNum1) + atoi(m_strNum2) ) );
            pEdt->SetWindowText(str);
        }
    }
}
 
/////////////////////////////////////////////////////////////////////////////
// CAlex12122Dlg message handlers
 
BOOL CAlex12122Dlg::OnInitDialog()
{
    CDialog::OnInitDialog();
 
    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon
    
    // TODO: Add extra initialization here
 
    return TRUE;  // return TRUE  unless you set the focus to a control
}
 
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.
 
void CAlex12122Dlg::OnPaint() 
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting
 
        SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
 
        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
 
        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}
 
// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CAlex12122Dlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}

mfc_Alex12122_v02.zip
скриншот
0
0 / 0 / 0
Регистрация: 24.04.2017
Сообщений: 5
30.04.2017, 01:53
Цитата Сообщение от stamp Посмотреть сообщение
v.02
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Alex12122Dlg.cpp : implementation file
//
// v.02
//
// mabe by stamp :-_)
//
 
#include "stdafx.h"
#include "Alex12122.h"
#include "Alex12122Dlg.h"
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
/////////////////////////////////////////////////////////////////////////////
// CAlex12122Dlg dialog
 
CAlex12122Dlg::CAlex12122Dlg(CWnd* pParent /*=NULL*/)
    : CDialog(CAlex12122Dlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CAlex12122Dlg)
        // NOTE: the ClassWizard will add member initialization here
    //}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
 
    m_strTxtFile    = "";
    m_strNum1       = "";
    m_strNum2       = "";
}
 
void CAlex12122Dlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CAlex12122Dlg)
        // NOTE: the ClassWizard will add DDX and DDV calls here
    //}}AFX_DATA_MAP
 
 
    DDX_Text(pDX, IDC_COMBO1, m_strNum1);
    if( pDX->m_bSaveAndValidate )
    {
        if( m_strNum1.IsEmpty() )
        {
            AfxMessageBox("Пожалуйста, введите значение.", MB_OK | MB_ICONEXCLAMATION);
            pDX->PrepareCtrl(IDC_COMBO1);
            pDX->Fail();
        }
    }
 
    DDX_Text(pDX, IDC_COMBO2, m_strNum2);
    if( pDX->m_bSaveAndValidate )
    {
        if( m_strNum2.IsEmpty() )
        {
            AfxMessageBox("Пожалуйста, введите значение.", MB_OK | MB_ICONEXCLAMATION);
            pDX->PrepareCtrl(IDC_COMBO2);
            pDX->Fail();
        }
    }
}
 
BEGIN_MESSAGE_MAP(CAlex12122Dlg, CDialog)
    //{{AFX_MSG_MAP(CAlex12122Dlg)
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    //}}AFX_MSG_MAP
    ON_CBN_EDITCHANGE(IDC_COMBO1, OnCombo1)
    ON_CBN_EDITCHANGE(IDC_COMBO2, OnCombo2)
    ON_EN_CHANGE(IDC_EDIT1, OnChangeEdit1)
    ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
    ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
    ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
END_MESSAGE_MAP()
 
void CAlex12122Dlg::OnCombo1() 
{
    CComboBox* ccb;
    ccb=(CComboBox*)GetDlgItem(IDC_COMBO1);
    if( ccb )
        ccb->GetWindowText(m_strNum1);
}
 
void CAlex12122Dlg::OnCombo2() 
{
    CComboBox* ccb;
    ccb=(CComboBox*)GetDlgItem(IDC_COMBO2);
    if( ccb )
        ccb->GetWindowText(m_strNum2);
}
 
void CAlex12122Dlg::OnChangeEdit1() 
{
    CEdit* pEdt=(CEdit*)GetDlgItem(IDC_EDIT1);
    if( pEdt )
    {
        pEdt->GetWindowText(m_strTxtFile);      
        
        BOOL bMode;
        if( m_strTxtFile.IsEmpty() )
            bMode = FALSE;
        else
            bMode = TRUE;
 
        CButton* pBt=(CButton*)GetDlgItem(IDC_BUTTON2);
        if( pBt ) pBt->EnableWindow(bMode);
    }
}
 
void CAlex12122Dlg::OnButton1()
{
    CFileDialog cfd(TRUE, ".txt", m_strTxtFile,
        OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY,
        "Текстовые документы (*.txt)|*.txt||");
    if( IDOK == cfd.DoModal() )
    {
        m_strTxtFile = cfd.GetPathName();
        CEdit* pEdt=(CEdit*)GetDlgItem(IDC_EDIT1);
        if( pEdt ) pEdt->SetWindowText(m_strTxtFile);
    }
}
 
void CAlex12122Dlg::OnButton2()
{
    if( m_strTxtFile.IsEmpty() ) return;
    
    CStdioFile f;
    if( !f.Open(m_strTxtFile, CFile::modeRead) )
    {
        CString strError;
        strError.Format("Не удалось открыть файл\n'%s'", m_strTxtFile);
        AfxMessageBox(strError, MB_OK | MB_ICONEXCLAMATION);
        return;
    }
 
    // Clear combobox.
    SendDlgItemMessage(IDC_COMBO1, CB_RESETCONTENT, (WPARAM)0, (LPARAM)0);
    SendDlgItemMessage(IDC_COMBO2, CB_RESETCONTENT, (WPARAM)0, (LPARAM)0);
 
    int nCount = 0; // Total line.
 
    BOOL bFound = FALSE;
    CString str, strLine;
 
    while( f.ReadString(strLine) )
    {
        for( int i=0; i<strLine.GetLength(); ++i )
        {
            if( bFound )
            {
                if( "," != strLine.Mid(i, 1) ||
                    " " != strLine.Mid(i, 1) )
                    str += strLine.Mid(i, 1);
            }
            else
            {
                if( "," == strLine.Mid(i, 1) ||
                    " " == strLine.Mid(i, 1) )
                {
                    SendDlgItemMessage(IDC_COMBO1, CB_ADDSTRING, 0,
                        (LPARAM)str.operator LPCTSTR());
                    str.Empty();
                    bFound = TRUE;
                }
                else
                    str += strLine.Mid(i, 1);
            }
        }
 
        if( " " == str.Left(1) )
            str.Replace(" ",  ""); 
 
        SendDlgItemMessage(IDC_COMBO2, CB_ADDSTRING, 0,
            (LPARAM)str.operator LPCTSTR());
 
        str.Empty();
        bFound = FALSE;
 
        ++nCount;
    }
    f.Close();
    
    SendDlgItemMessage(IDC_COMBO1, CB_SETCURSEL, (WPARAM)0, (LPARAM)0);
    SendDlgItemMessage(IDC_COMBO2, CB_SETCURSEL, (WPARAM)0, (LPARAM)0);
}
 
void CAlex12122Dlg::OnButton3()
{
    if( UpdateData(TRUE) )
    {
        CEdit* pEdt=(CEdit*)GetDlgItem(IDC_EDIT4);
        if( pEdt )
        {
            CString str;
            str.Format("%d", ( atoi(m_strNum1) + atoi(m_strNum2) ) );
            pEdt->SetWindowText(str);
        }
    }
}
 
/////////////////////////////////////////////////////////////////////////////
// CAlex12122Dlg message handlers
 
BOOL CAlex12122Dlg::OnInitDialog()
{
    CDialog::OnInitDialog();
 
    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon
    
    // TODO: Add extra initialization here
 
    return TRUE;  // return TRUE  unless you set the focus to a control
}
 
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.
 
void CAlex12122Dlg::OnPaint() 
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting
 
        SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
 
        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
 
        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}
 
// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CAlex12122Dlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}

Вложение 826771
скриншот
Тут немного не то, мне бы примерно как на скрине сделать, у меня получилось считать первые два значения в первые две строки и осталось перейти на след строчку блокнота и, как я понял, так же как и ты до этого делал считать оставшиеся в 3 и 4
Миниатюры
Чтение из файла в строку (в MFC)  
0
Заблокирован
30.04.2017, 11:45
Фенрис, смотрите работу в цикле чтения файла, уберите некоторые моменты,
оставьте лишь замена определенного символа (это член класса CString - Replace).
Остальное - ваша работа с отладчиком.
0
0 / 0 / 0
Регистрация: 24.04.2017
Сообщений: 5
30.04.2017, 18:20
Значит идея состоит в том, что когда я считываю 3 и 4 значение я просто вставляю код для 1 и 2, но с заменой при помощи replace? Осталось только понять как реализовать замену значений из первой строки блокнота на значения из второй..
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
30.04.2017, 18:20
Помогаю со студенческими работами здесь

MFC Чтение из файла в Lst Box
Доброе время суток. Мне нужно записать содержимое файла в List Box. Подскажите как. Спасибо. Добавлено через 1 час 19 минут Ну...

Чтение из файла и создание объектов MFC
Rect MyRect; CPaintDC dc(this); char buff; int x1,x2,x3,x4,i=1; ifstream f(&quot;E\\data.txt&quot;); while(!f.eof()) { f&gt;&gt;buff;...

Чтение файла в строку
Доброго времени суток. Имеется задача: организовать проверку пароля (пароль хранится в текстовом файле). столкнулся с проблемой ввода в...

Чтение из файла в строку
Всем привет! Подскажите, пожалуйста, как прочитать весь текст из файла в переменную string! что-то туплю, не могу понять.. спасибо!

Чтение из файла в строку
выручайте! нужно считать текст из i-ого файла, который лежит в папке assets, и отобразить его в textView. можете объяснить, в чем ошибка? ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
12
Ответ Создать тему
Новые блоги и статьи
сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и источниками (напряжения, ЭДС и тока). Найти токи и напряжения во всех элементах. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru