首页 > 解决方案 > C++读取功能改进,可以读取多个文件

问题描述

我有一点改进,我正在制作我的图灵机,它从 txt 文件中读取参数,然后在终端中执行磁带。我想要做的是让它从多个 txt 文件中读取,然后执行多个磁带。因为我是编程新手,所以我很难理解我应该使用线程还是创建多个读取函数并稍后将参数放入 while 循环中,也许有人可以给我一个建议?

这是阅读功能

void reader(int &head, string &tape, string a[N][n])
{
    ifstream df;
    df.open("samples/1.txt");
    df >> head;
    df >> tape;
    rule = tape.size(); // how many symbols we have in our line
    for (int i = 0; i < N; i++)
        if (df >> a[i][0])
        {
            for (int j = 1; j < n; j++)
            {
                df >> a[i][j];
            }
        }
        else
        {
            length = i; //how many lines of rules we have
            i = N;
        }
    df.close();
}

而while循环

while (d != "X")
{
    for (int y = 0; y < length; y++)
        if ((d == a[y][0]) && (p == a[y][1]))
        {
            tape[position] = a[y][2][0];
            if (a[y][3] == "L") // if string equals L (or R) it switches/moves
                position--;
            else
                position++;
            p = tape[position];
            d = a[y][4];
            y = length;
        }
    for (int j = 0; j < rule; j++)
    {
        cout << tape[j];
        //Sleep(1);
    }
    cout << endl;
    system("CLS");
}

标签: c++functionwhile-loop

解决方案


C++ std::thread文档非常简单。这是您如何实现这一目标的方法。

#include <string>
#include <thread>
#include <vector>

using namespace std;

void doStuff(std::string fileName)
{
    // call your file reading and trigger the Turing Machine.
}

int main()
{
    vector<string> fileNames = {"file1.txt", "file2.txt"};
    vector<thread> threads;

    for ( string fileName : fileNames)
        threads.push_back(thread(doStuff, fileName)); // start a thread to run doStuff() with fileName as the argument.

    for (auto t : threads)
        t.join();

}

您可以调整文件阅读以相应地使用fileNamein doStuff()


推荐阅读