我有一个文件" first.txt":
Chun mee |Wuyi |Genmai |
Pu-erth |Green |Flower mix |
Lightly sweet|Strong,smooth|Fresh, strong|
这里' |'是分隔符,第一行在每个块中有10个符号(块是分隔符之间的空格),第二行是11,第三行是13。 我想像这样组合这些行并写下来(" rec.txt"):
Chun mee '\t'Pu-erth '\t'Lightly sweet
Wuyi '\t'Green '\t'Strong,smooth
Genmai '\t'Flower mix '\t'Fresh, strong
这是我的代码:
#include <iostream>
#include <fstream>
#include <string.h>
#include <cstdlib>
#include <fstream>
#include <limits>
using namespace std;
fstream& go_line(fstream& file, unsigned int num){
for(int i=0; i < num - 1; ++i){
file.ignore(numeric_limits<streamsize>::max(),'\n');
}
return file;
}
void func(int iter_num){
fstream file;
fstream file_exist;
string str;
file_exist.open("first.txt");
file.open("rec.txt", ios::in | ios::out | ios:: trunc | ios::binary);
if (iter_num < 3){ //iter_num - num of iterations (lines)
for(int i = 0; i < iter_num; i++ ){
for(int t = 1; t< 4; t++ ){ //t-num of columns
if(i>0 && t==1){
file<<endl;
}
if(i == 0){
go_line(file_exist, t);
getline (file_exist, str, '|');
file_exist.seekp(0, ios::beg);
file<<str<<'\t';
}
else{
switch(t){
case 1:
//cout<<"case1 "<<endl;
file_exist.seekp((i*10)+1, ios::beg);
go_line(file_exist, t);
getline (file_exist, str, '|');
file<<str<<'\t';
break;
case 2:
//cout<<i<<endl;
go_line(file_exist, t);
file_exist.seekp((i*11)+1, ios::beg);
getline (file_exist, str, '|');
file<<str<<'\t';
case 3:
//cout<<i<<endl;
go_line(file_exist, t);
file_exist.seekp((i*13)+1, ios::beg);
getline (file_exist, str, '|');
file<<str<<'\t';
}//switch
}//else
}//for
}//for
}//if
}//func
int main(){
int n = 3;
func(n);
return 0;
}
问题是: 例如,如果2个seekp()不在新行的开头,那么它就在第一行。但这个想法是 - 将它设置在新线的开头并获得&#34; Green&#34;因为&#34;武夷&#34;。所以,它工作不正确,我没有想法。 谢谢你的帮助!
答案 0 :(得分:1)
一个简单的例子:
#include <string>
#include <vector>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <sstream>
using namespace std;
int main()
{
ifstream to_format("test/test.txt");
ofstream formatted("test/formatted.txt");
vector<vector<string>> item_matrix; //
// Populating the matrix.
for (string line; getline(to_format, line);)
{
item_matrix.push_back({});
stringstream line_(line); // string stream used for split the line according to the separator '|'
for (string item; getline(line_, item, '|');)
{
item_matrix.back().push_back(item); // Add items to the last row.
}
}
// Output the matrix to file.
// This assume all lines in the original file have the same number of blocks.
vector<string> new_lines;
for (int i = 0; i < item_matrix[0].size(); i++)
{
new_lines.push_back({});
for_each(item_matrix.begin(), item_matrix.end(), [&](vector<string> row){
formatted << setw(25) << left << row[i];
});
formatted << endl;
}
return 0;
}
示例输入:
Chun mee |Wuyi |Genmai |
Pu-erth |Green |Flower mix |
Lightly sweet|Strong,smooth|Fresh, strong|
示例输出:
Chun mee Pu-erth Lightly sweet
Wuyi Green Strong,smooth
Genmai Flower mix Fresh, strong
答案 1 :(得分:0)
你使用的go_line函数继续读取,直到文件结束,这样循环无效read this