在一个文件中混合多个文件行

问题描述 投票:-1回答:1

我正在使用Round Robin调度程序模拟器,因此我有4个文件A.txt,B.txt,C.txt,D.txt。每个代表一个过程,其中的每一行都是一个指令。每个都有o,p,q,r行。所以我想从这些文件中创建一个文件RR.txt。即。量子= 8。

8 lines of file A
8 lines of file B
8 lines of file C 
8 lines of file D
next 8 lines of file A
next 8 lines of file B
next 8 lines of file C
next 8 lines of file D
...
and so on until run out of lines on all files.

我已经有了数组上文件的名称

string names_processes[number_of_processes];

并从每个我获得的行数创建一个函数

int countLines(const string& inputFile){
    int counter=0;ifstream file(inputFile);string str;
    while (getline(file, str)) {counter++;}
    return counter;
  }

并使用它

int o = countLines(names_processes[0]); //file A.txt
int p = countLines(names_processes[1]); //file B.txt
int q = countLines(names_processes[2]); //file C.txt
int r = countLines(names_processes[3]); //file D.txt
c++
1个回答
0
投票

假设你需要从文件中获取8行,你可以这样做:

std::vector<string> getLines(const string& inputFile){
    int counter;
    std::vector<string> lines;
    ifstream file(inputFile);
    std::string str;
    for(counter = 0; getline(file, str) && counter < 8; counter++){
        lines.push_back(str);
    }
    return lines;
}

如果达到eof或读取8行,getline(file, str) && counter < 8将退出循环。

© www.soinside.com 2019 - 2024. All rights reserved.