将参数传递给void函数

时间:2017-12-08 20:50:25

标签: c++

如何将参数行传递给void?它保持显示错误,数据类型应该是

  

行[100] [260]

我尝试其他方式,如

  

wchar_t * line [] []

仍然不能

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

  void test(DWORD a, wchar_t * line[])
    {

        unsigned int i;

        for (i = 0; i < a; i++)
        {
            wcout << line[i];
        }

    }

    int main()
    {
        FILE *pFile;
        wchar_t *file = L"d:\\a.txt";
        wchar_t line[100][MAX_PATH];
        unsigned int a = 0;
        if (_wfopen_s(&pFile, file, L"r, ccs = UNICODE") == 0)
        {
            while (fgetws(line[a], 100, pFile))
            {
                a++;
            }
        }

        test(a, line);

        return 0;
    }

谢谢

1 个答案:

答案 0 :(得分:0)

您的函数需要一个指向以null结尾的字符串的一维指针数组。但是你试图将它传递给二维数组的字符。它们不是同一件事!

至少,您可以创建第二个数组,其中包含指向第一个数组元素的指针,例如:

#include "stdafx.h"

#include <iostream>
#include <fstream>

#include <windows.h>

void test(DWORD a, wchar_t * lines[])
{
    for (unsigned int i = 0; i < a; ++i) {
        std::wcout << lines[i] << std::endl;
    }
}

int main()
{
    FILE *pFile;
    wchar_t *file = L"d:\\a.txt";
    wchar_t lineData[100][MAX_PATH];
    wchar_t* lines[100];
    wchar_t *line;

    unsigned int a = 0;
    if (_wfopen_s(&pFile, file, L"r, ccs = UNICODE") == 0)
    {
        do
        {
            line = lineData[a];

            if (!fgetws(line, MAX_PATH, pFile))
                break;

            size_t len = wcslen(line);
            if ((len > 0) && (line[len-1] == L'\n'))
                line[--len] = 0;

            lines[a] = line;
        }
        while (++a < 100);

        fclose(pFile);
    }

    test(a, lines);

    return 0;
}

话虽如此,既然你正在使用C ++,你应该使用C ++功能而不是C功能来读取文件,例如:

#include "stdafx.h"
#include <windows.h>

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

void test(const std::vector<std::wstring> &lines)
{
    for (std::wstring &line : lines) {
        std::wcout << line << std::endl;
    }

    /* or: prior to C++11:

    for (std::size_t i = 0; i < lines.size(); ++i) {
        std::wcout << lines[i] << std::endl;
    }

    or:

    for (std::vector<std::wstring>::iterator iter = lines.begin(); iter != lines.end(); ++iter) {
        std::wcout << *iter << std::endl;
    }
    */
}

int main()
{
    std::vector<std::wstring> lines;
    std::wstring line;

    std::wifstream file(L"d:\\a.txt");
    if (file.is_open())
    {
        while (std::getline(file, line)) {
            lines.push_back(line);
        }
        file.close();
    }

    test(lines);

    return 0;
}