c++ - 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++ 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();
}
您可以调整文件阅读以相应地使用fileName
in doStuff()
。
推荐阅读
- python - Django WhiteNoise 配置与 WhiteNoise v4.0 不兼容
- javascript - 数组映射函数
- .net-core - 是否可以将库注入库?
- python - 为什么我不能在 Pandas 中创建源自 drop 方法的对象?
- scala - spark递归修复类中的循环引用
- dart - 在 dart 中调用父构造函数之前执行代码
- amazon-web-services - AWS EMR Livy 会话状态已终止
- tensorflow - 注意力层输出形状问题
- r - 如何将日期列表转换为 POSIXlt 对象?
- javascript - .then() 中的 Promise.reject 返回未定义