Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
Другие темы раздела
C++ Программа, печатающая числа от 1 до 4 Ps: Тема подразумевает собой не 1 вопрос а при постепенном изучении C++ - постановка нового вопроса - задачи, поетому и выбрал такое название темы Одна тема - один вопрос. Тема переименована. Задача №1 // Напишите программу, которая печатает числа от 1 до 4 на одной // и той же строке, так что соседние числа разделены одним пробелом. #include <iostream.h> #include <cstdlib> #include... https://www.cyberforum.ru/ cpp-beginners/ thread169006.html теория C++
какя разница между кодами ? if(a>b) a++; b++; и if(a>b) a++;
C++ Вычислить и вывести на экран в виде значений функции https://www.cyberforum.ru/ cpp-beginners/ thread168979.html
вычислить и вывести на экран в виде таблицы значения функции,заданной с помощью ряда Тейлора,на интервале от Хнач до Хкон с шагом dx с точностью e (e=0.001) ln(1+x)/(1-x)=2∑ (x^(2k+1))/(2k+1) k=0,...,n -1<x<1 Помогите пожалуйста , а то я вообще не знаю , что такое ряд Тейлора . Очень надо - первая зачетная работа по программированию в универе ! Только , если можно , как можно проще)...
C++ Программа для вычисления выражения y=2 lg (x)+5 https://www.cyberforum.ru/ cpp-beginners/ thread168959.html
Помогите пожалуйста написать программу для вычисления выражения y=2 lg (x)+5.x и y - вещественные числа.
C++ Функция нахождения минимального элемента заданного столбца матрицы
Написать библиотеку функций для работы с квадратной целочисленной матрицей а)Функция для инициализации массива случайными числами из диапазона -50 до 25 б)Функция для вывода этого массива на экран в)Функция, какая получает матрицу и номер столбца и возвращает минимальный элемент из этого столбца Название темы должно отражать ее содержимое. В дальнейшем относитесь к именованию тем более...
C++ Определить MAX элемент в первом столбце и MIN элемент в последнем столбце матрицы дано целочисленная матрица n x m определить: 1. MAX элемент в первом столбце и MIN элемент в последнем столбце. 2 MAX элемент во второй строке и MIN элемент в предпоследней строке и указать их место нахождения https://www.cyberforum.ru/ cpp-beginners/ thread168932.html
C++ Операторы сложения и присваивания здравствуйте. допустим у меня есть класс A. В этом классе содержатся функции : A operator=(A &ob); friend A operator+(A &ob1, A &ob2); В главной функции main : A a,b,c; /*********** здесь операции только над объектами a и b. ************/ https://www.cyberforum.ru/ cpp-beginners/ thread168930.html Считывание нажатия клавиш с клавиатуры C++
как сделать так чтобы программа завершалась при нажатие какой-то определенной клавиши?
C++ использована неинициализированная локальная переменная "info" #include <iostream> using namespace std; int main(){ enum paytype{CARD,CHECK}; struct{ paytype ptype; union { char card; long check; https://www.cyberforum.ru/ cpp-beginners/ thread168882.html C++ Перевод длинного двоичного числа в десятичную СС Как можно перевести число из двоичной системы счисления в десятичную ели число длиной в 100-300 знаков... https://www.cyberforum.ru/ cpp-beginners/ thread168878.html
C++ Определить, содержит ли последовательность хотя бы одно простое число
Вводится последовательность из N целых положительных элемен-тов. Определить, содержит ли последовательность хотя бы одно простое чис¬ло. Для определения простого числа создать функцию. Подскажите как делать,пожалуйста.
C++ массив и возрастающая последовательность #include <iostream> using namespace std; void main() { int t; int n; for (int i=0; i<5; i++) { cin >> t; https://www.cyberforum.ru/ cpp-beginners/ thread168850.html
0 / 0 / 0
Регистрация: 20.10.2009
Сообщений: 11
0

Работает только первый wcout - C++ - Ответ 981390

24.09.2010, 22:33. Показов 1477. Ответов 0
Метки (Все метки)

Author24 — интернет-сервис помощи студентам
Доброго времени суток!

Обо всём по порядку. Есть программа, выводящая MAC-адреса всех сетевых устройств, а также все открытые ресурсы сети, вот весь код на всякий случай:

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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#define _UNICODE
#include "stdafx.h"
#include <windows.h>
#include <wincon.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <Winnetwk.h>
#include <iostream>
#include <clocale>
#include <tchar.h>
#include <string>
using namespace std;
 
BOOL EnumerateFunc(LPNETRESOURCE);
 
/*
The ADAPTER_STATUS structure contains information about a network adapter. This structure 
is pointed to by the ncb_buffer member of the NCB structure. ADAPTER_STATUS is followed by 
as many NAME_BUFFER structures as required to describe the network adapters on the system.
*/
ADAPTER_STATUS Adapter;
 
void GetMacAddresses()
{
    /*
    The NCB structure represents a network control block. It contains information about the 
    command to perform, an optional post routine, an optional event handle, and a pointer to 
    a buffer that is used for messages or other data. A pointer to this structure is passed 
    to the Netbios function. 
    */
    NCB ncb;
    
    UCHAR uRetCode;
    char MacAddress[50];
    memset(&ncb, 0, sizeof(ncb));
    
    /*
    ncb_command : Specifies the command code and a flag that indicates whether the NCB structure 
    is processed asynchronously.
    NCBRESET : Resets a LAN adapter. An adapter must be reset before it can accept any other 
    NCB command that specifies the same number in the ncb_lana_num member.
    */
    ncb.ncb_command = NCBRESET;
 
    /*
    The Netbios function interprets and executes the specified network control block (NCB).
    For synchronous requests, the return value is the return code in the NCB structure. That value 
    is also returned in the ncb_retcode member of the NCB structure.
    */
    uRetCode = Netbios( &ncb );
    
    /*void *memset(void *dest, int c, size_t count);
    Sets buffers to a specified character.
    Parameters:
    dest - Pointer to destination.
    c - Character to set.
    count - Number of characters.
    Return Value: The value of dest.
    Remarks: Sets the first count characters of dest to the character c.
    */
    memset(&ncb, 0, sizeof(ncb));
    
    /*
    NCBENUM : Enumerates LAN adapter (LANA) numbers. When this code is specified, 
    the ncb_buffer member points to a buffer to be filled with a LANA_ENUM structure. 
    NCBENUM is not a standard NetBIOS 3.0 command.
    */
    ncb.ncb_command = NCBENUM;
    
    /*
    The LANA_ENUM structure contains the numbers for the current LAN adapters. 
    The LANA_ENUM structure is pointed to by the ncb_buffer member of the NCB structure 
    when an application issues the NCBENUM command. Members:
    length - Specifies the number of valid entries in the array of LAN adapter numbers.
    lana - Specifies an array of LAN adapter numbers.
    */
    LANA_ENUM myLanaEnum;
    
    /*
    ncb_buffer : Pointer to the message buffer. The buffer must have write access. Its 
    uses are as follows:
    NCBSEND - Contains the message to be sent.  
    NCBRECV - Receives the message.  
    NCBSSTAT - Receives the requested status information. 
    */
    ncb.ncb_buffer = (unsigned char *) &myLanaEnum;
    
    /*
    ncb_length : Specifies the size, in bytes, of the message buffer. For receive commands, 
    this member is set by the Netbios function to indicate the number of bytes received.
    If the buffer length is incorrect, the Netbios function returns the NRC_BUFLEN error code.
    */
    ncb.ncb_length = sizeof(LANA_ENUM);
 
    uRetCode = Netbios( &ncb );
 
    if(uRetCode==0) 
    {
        for (long i = 0; i < myLanaEnum.length; ++i)
        {   
            ncb.ncb_command = NCBRESET;
 
            /*
            Specifies the LAN adapter number. This zero-based number corresponds to a particular transport
            provider using a particular LAN adapter board.
            */
            ncb.ncb_lana_num = myLanaEnum.lana[i];
 
            uRetCode = Netbios( &ncb );
    
            /*
            Retrieves the status of either a local or remote adapter. When this code is specified, 
            the ncb_buffer member points to a buffer to be filled with an ADAPTER_STATUS structure, 
            followed by an array of NAME_BUFFER structures.
            */
            ncb.ncb_command = NCBASTAT;
 
            /*
            ncb_callname : Specifies the name of the remote application. Trailing-space characters 
            should be supplied to make the length of the string equal to NCBNAMSZ.
            */
            strcpy( (char *) ncb.ncb_callname, "*   " );
            ncb.ncb_buffer = (unsigned char *) &Adapter; 
            ncb.ncb_length = sizeof(Adapter);
            uRetCode = Netbios( &ncb );
            printf("LANA_ENUM lana[%i]: %i, MAC Address: ",i,myLanaEnum.lana[i]);
            if(uRetCode==0)
            { 
                sprintf(MacAddress, "%02X-%02X-%02X-%02X-%02X-%02X\n",
                Adapter.adapter_address[0], 
                Adapter.adapter_address[1], 
                Adapter.adapter_address[2], 
                Adapter.adapter_address[3], 
                Adapter.adapter_address[4], 
                Adapter.adapter_address[5]); 
            }
            printf(MacAddress);
        }
    }
}
 
wchar_t ctw(char c)
{
    std::pair<int,int> ctw_pairs[64];
    int i = -32;
    int j = 1072;
    int k = 0;
 
    while ( (i != 0) && (j != 1104) )
    {
        ctw_pairs[k].first = i;
        ctw_pairs[k].second = j;
        i++;
        j++;
        k++;
    }
    i = -64;
    j = 1040;
    while ( (i != -32) && (j != 1072) )
    {
        ctw_pairs[k].first = i;
        ctw_pairs[k].second = j;
        i++;
        j++;
        k++;
    }
 
    k = 0;
    int n = (int) c;
    while (ctw_pairs[k].first != n)
        k++;
    return ctw_pairs[k].second;
}
 
void DisplayStruct(LPNETRESOURCE resourse)
{
    /*
    LPTSTR : An LPWSTR if UNICODE is defined, an LPSTR otherwise.
    LPWSTR : A pointer to a null-terminated string of 16-bit Unicode characters:
             typedef WCHAR *LPWSTR;
    LPSTR  : A pointer to a null-terminated string of 8-bit Windows (ANSI) characters:
             typedef CHAR *LPSTR;
    */
    
    LPSTR s_lpRemoteName = resourse->lpRemoteName;
    int lpRemoteName_length = 0;
    while(s_lpRemoteName[lpRemoteName_length] != '\0')
        lpRemoteName_length++;
 
    wchar_t *w_lpRemoteName = new wchar_t[lpRemoteName_length] ;
    for (int i = 0; i < lpRemoteName_length; i++)
        if ( (int)s_lpRemoteName[i] > 0 )
            w_lpRemoteName[i] = s_lpRemoteName[i];
        else
            w_lpRemoteName[i] = ctw(s_lpRemoteName[i]);
 
    wchar_t aa[] = L"по-русски";
    std::wcout << w_lpRemoteName << aa << std::endl;
 
    EnumerateFunc(resourse);
}
 
BOOL EnumerateFunc(LPNETRESOURCE lpnr)
{ 
    /*
    DWORD : A 32-bit unsigned integer. The range is 0 through 4294967295 decimal.
    This type is declared in WinDef.h as follows:
    typedef unsigned long DWORD;
    */
    DWORD dwResult, dwResultEnum;
 
    /*
    HANDLE : A handle to an object.
    This type is declared in WinNT.h as follows:
    typedef PVOID HANDLE;
 
    Дескриптор (handle) - число, которое задает номер какого-либо ресурса 
    (блок памяти, файл, курсор, шрифт, окно и т. п.) при работе с ним. 
    Дескриптор используется обычно при работе через некоторый интерфейс (API), 
    причем смысл значения дескриптора скрыт за этим интерфейсом. Например, 
    дескриптор блока памяти может означать номер ячейки в таблице адресов 
    блоков памяти; поскольку пользователь API работает с дескриптором, а 
    не с указателем, адрес размещения блока памяти может менятся, и это не 
    скажется на работе с ним через дескриптор.
    */
    HANDLE hEnum;
 
    DWORD cbBuffer = 16384;      // 16K is a good size
    DWORD cEntries = -1;         // enumerate all possible entries
 
    /*
    The NETRESOURCE structure contains information about a network resource.
    */
    LPNETRESOURCE lpnrLocal = NULL;     // pointer to enumerated structures
    
    DWORD i;
    //
    // Call the WNetOpenEnum function to begin the enumeration.
    //
 
    DWORD tmp1 = NO_ERROR;
 
    /*
    The WNetOpenEnum function starts an enumeration of network resources or existing connections.
    Parameters:
    DWORD dwScope : Scope of the enumeration; RESOURCE_GLOBALNET - Enumerate all resources on the network.
    DWORD dwType : Resource types to be enumerated; RESOURCETYTPE_ANY - All resources.
    DWORD dwUsage : Resource usage type to be enumerated; 0 - All resources.
    LPNETRESOURCE lpNetResource : Pointer to a NETRESOURCE structure that specifies the container to enumerate.
                                  If this parameter is NULL, the root of the network is assumed. 
    LPHANDLE lphEnum : Pointer to an enumeration handle that can be used in a subsequent call to WNetEnumResource.
    If the function succeeds, the return value is NO_ERROR.
    */
    dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, lpnr, &hEnum);
 
    if (dwResult != NO_ERROR)
    {  
        return FALSE;
    }
 
    /*
    GlobalAlloc : Allocates the specified number of bytes from the heap.
    UINT uFlags : The memory allocation attributes. 
                  GPTR - Combines GMEM_FIXED and GMEM_ZEROINIT;
                  GMEM_FIXED - Allocates fixed memory. The return value is a pointer;
                  GMEM_ZEROINIT - Initializes memory contents to zero;
    SIZE_T dwBytes : The number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies 
                     GMEM_MOVEABLE, the function returns a handle to a memory object that is marked as discarded.
    If the function succeeds, the return value is a handle to the newly allocated memory object.
    If the function fails, the return value is NULL.
    */
    lpnrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer);
    if (lpnrLocal == NULL) 
        return FALSE;
 
    do
    {  
        /*
        The ZeroMemory macro fills a block of memory with zeros.
        void ZeroMemory(PVOID Destination, SIZE_T Length);
        Parameters:
        Destination : Pointer to the starting address of the block of memory to fill with zeros. 
        Length : Size of the block of memory to fill with zeros, in bytes.
        */
        ZeroMemory(lpnrLocal, cbBuffer);
 
        /*
        The WNetEnumResource function continues an enumeration of network resources that was 
        started by a call to the WNetOpenEnum function.
 
        DWORD WNetEnumResource(HANDLE hEnum, LPDWORD lpcCount, LPVOID lpBuffer, LPDWORD lpBufferSize);
 
        Parameters:
        hEnum : Handle that identifies an enumeration instance. This handle must be returned by the 
                WNetOpenEnum function. 
        lpcCount : Pointer to a variable specifying the number of entries requested. If the number 
                   requested is –1, the function returns as many entries as possible. If the function 
                   succeeds, on return the variable pointed to by this parameter contains the number 
                   of entries actually read.
        lpBuffer : Pointer to the buffer that receives the enumeration results. The results are returned 
                   as an array of NETRESOURCE structures. Note that the buffer you allocate must be large 
                   enough to hold the structures, plus the strings to which their members point. The buffer 
                   is valid until the next call using the handle specified by the hEnum parameter. The 
                   order of NETRESOURCE structures in the array is not predictable.
        lpBufferSize : Pointer to a variable that specifies the size of the lpBuffer parameter, in bytes. 
                       If the buffer is too small to receive even one entry, this parameter receives the 
                       required size of the buffer.
        */
        dwResultEnum = WNetEnumResource(hEnum, &cEntries, lpnrLocal, &cbBuffer);
 
        if (dwResultEnum == NO_ERROR)
        {
            for(i = 0; i < cEntries; i++)
            {
                DisplayStruct(&(lpnrLocal[i]));
            }
        }
 
        else 
            if (dwResultEnum != ERROR_NO_MORE_ITEMS)
            {
                break;
            }
    }
    while(dwResultEnum != ERROR_NO_MORE_ITEMS);
 
    GlobalFree((HGLOBAL)lpnrLocal);
    dwResult = WNetCloseEnum(hEnum);
    if(dwResult != NO_ERROR)
    { 
        return FALSE;
    }
    std::cout << std::endl;
    return TRUE;
}
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    setlocale(LC_CTYPE, "");
 
    GetMacAddresses();
    getchar();
 
    EnumerateFunc(0);
    getchar();
 
    return 0;
}
извиняюсь за обширные комменты)
ф-я GetMacAdress() выводит MAC-адреса, и к ней претензий нет
ф-я EnumerateFunc() рекурсивно проходит по всем открытым сетевым ресурсам (среди открытых сетевых ресурсов есть такие, имена которых на русском), вывод имени сетевого ресурса осуществляет ф-я DisplayStruct(), которая вызывает следующую EnumerateFunc(), пока есть куда стремиться .
ф-я ctw() "конвертирует" символ char в символ wchar_t
собственно, проблема находится в предпоследней строке ф-ии DisplayStruct. Самый первый w_lpRemoteName выводится с помощью wcout, а аа уже не выводится. При дальнейших вызовах этой функции ни w_lpRemoteName, ни aa не выводятся. в чём проблема?

Вернуться к обсуждению:
Работает только первый wcout C++
0
Заказать работу у эксперта
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
24.09.2010, 22:33
Готовые ответы и решения:

Программа ищет первый столбик где находятся только непарный елементы!Почему не работает Иф?
#pragma hdrstop #include&lt;conio.h&gt; #include&lt;iostream.h&gt; #include&lt;stdlib.h&gt; #include &lt;iomanip.h&gt;...

Error 1 error C2447: '{' : missing function header (old-style formal list?) и почему не работает ? и подскажите как пользоваться wcout
Всем привет я начинаю обучаться программированию и сегодня столкнулся с такой проблемой...

Использование wcout
В чем ошибка? Компиляция прошла без проблем. В командной строке пишет просто &quot;Для продолжения...

Std::wcout не выводит сообщение
Здравствуйте. Вот в таком коде : int _tmain(int argc, _TCHAR* argv) {...

0
24.09.2010, 22:33
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
24.09.2010, 22:33
Помогаю со студенческими работами здесь

Wcout: Вывод непонятных символов
Всем доброго времени суток. Пишу прогу, которая вычленит из html-файла определенные тэги и выведет...

wcout, wfstream в Code Blocks
Не пойму, почему компилятор не определяет wcout, wfstream. #include &lt;iostream&gt;, #include &lt;fstream&gt;,...

Cout и wcout. Русские буквы
Здравствуйте. При попытке считать из текстового файла, который содержит строку - &quot;Привет!&quot; - и...

Записывать только первый елемент
Добрый вечер. Нуждаюсь в помощь,записывает в файл только первые три строчки и все, остальные не...

0
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru