将函数输出分配给变量

时间:2012-12-03 17:04:02

标签: c++ visual-c++

我有这个:

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Iphlpapi.h>
#include <Assert.h>
#include <sstream>

#pragma comment(lib, "iphlpapi.lib")

using namespace std;

// Prints the MAC address stored in a 6 byte array to stdout
static void PrintMACaddress(unsigned char MACData[])
{

    printf("%02X-%02X-%02X-%02X-%02X-%02X", 
        MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);

}

// Fetches the MAC address and prints it
static void GetMACaddress(void)
{
    IP_ADAPTER_INFO AdapterInfo[16];            // Allocate information for up to 16 NICs
    DWORD dwBufLen = sizeof(AdapterInfo);       // Save the memory size of buffer

    DWORD dwStatus = GetAdaptersInfo(           // Call GetAdapterInfo
        AdapterInfo,                            // [out] buffer to receive data
        &dwBufLen);                             // [in] size of receive data buffer
    assert(dwStatus == ERROR_SUCCESS);          // Verify return value is valid, no buffer overflow

    PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;// Contains pointer to current adapter info
    do {
        PrintMACaddress(pAdapterInfo->Address); // Print MAC address
        pAdapterInfo = pAdapterInfo->Next;      // Progress through linked list
    }
    while(pAdapterInfo);                        // Terminate if last adapter
}

    int _tmain(int argc, _TCHAR* argv[])
    {
    char mac[100];

        GetMACaddress(); // output is 00-19-D7-53-2D-14

    std::stringstream buffer;
    buffer << "Text" << std::endl;
    cout << buffer.str();
        return 0;
    }

我的问题是如何将函数GetMACaddress();输出分配给变量。这个:mac = GetMACaddress(); // output is 00-19-D7-53-2D-14没有用。请帮帮我。谢谢。

返回MAC地址的数据类型为unsigned char

3 个答案:

答案 0 :(得分:0)

如果返回mac地址的数据类型为unsigned char,则可以将其存储在其中。

unsigned char output = GetMACaddress() ;

如果它是字符串,请使用std::string存储返回的mac地址,如果你说的是模式00-19-D7-53-2D-14的输出。

std::string output = GetMACaddress() ;

如果是其他类型,您可以让编译器在运行时决定。如果您使用的是C ++ 11,则可以使用autodecltype

auto return_val = GetMACaddress() ;

答案 1 :(得分:0)

您需要将stdout缓冲区重定向到字符串流,如下所示:

stringstream ss;
streambuf* old = std::cout.rdbuf(ss.rdbuf()); // redirect stdout, and also save the old one

GetMACAddress();

string theStr = ss.str();
cout << theStr << endl;

// when you are done, redirect back to the "real" stdout
cout.rdbuf(old);

答案 2 :(得分:0)

您的函数PrintMACaddress打印MAC地址;你需要一个类似的函数来接收unsigned char MACData[]但返回一个MAC地址而不是打印它。

// Converts the MAC address stored in a 6 byte array to a string
std::string ConvertMACaddressToString(unsigned char MACData[])
{
    ...
}

要实现它,请先按printf替换sprintf

char result[18]; // 18 bytes are just enough to hold the MAC address
sprintf(result, "%02X-%02X-%02X-%02X-%02X-%02X", 
    MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);

然后从函数返回值:

return result;