第一个文件 file1.csv
4.001
3.002
3.003
4.004
第二个文件 file2.csv
100.8
102.4
121.9
107.5
我想要格式为
的最终文件 final.csv4.001 100.8
3.002 102.4
3.003 121.9
4.004 107.5
答案 0 :(得分:3)
首先,遗憾的是,提问者没有做出任何努力来解决这个常见问题。或许这是他的作业? :)
Qt的做法:
QFile file1("file1.csv");
file1.open(QIODevice::ReadOnly | QIODevice::Text);
QFile file2("file2.csv");
file2.open(QIODevice::ReadOnly | QIODevice::Text);
QFile res("final.csv");
res.open(QIODevice::WriteOnly);
QTextStream stream;
stream.setDevice(&res);
while (file1.atEnd() == false || file2.atEnd() == false)
{
QByteArray s1 = file1.readLine();
if (s1.endsWith("\n"))
{
s1.chop(1);
}
QByteArray s2 = file2.readLine();
if (s2.endsWith("\n"))
{
s2.chop(1);
}
stream << s1 << " " << s2 << "\n";
}
file1.close();
file2.close();
res.close();
答案 1 :(得分:0)
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
std::vector<std::string>
split_string(std::string src, std::string delim) {
std::vector<std::string> tokens;
std::string tmp = src;
size_t i = 0;
while (i < tmp.length()) {
int oi = i;
i = tmp.find(delim, i);
if(i != std::string::npos) {
tokens.push_back(tmp.substr(oi, i - oi));
} else {
tokens.push_back(tmp.substr(oi));
break;
}
i += delim.length();
}
return tokens;
}
int
main(int argc, char* argv[]) {
std::ifstream file3("file3.csv");
std::string buf3;
std::getline(file3, buf3);
file3.close();
std::ifstream file2("file2.csv");
std::string buf2;
std::getline(file2, buf2);
file3.close();
auto vec3 = split_string(buf3, " ");
auto vec2 = split_string(buf2, " ");
int size = vec3.size();
for (int n = 0; n < size; n++) {
std::cout << vec3[n] << " " << vec2[n];
if (n < size - 1)
std::cout << " ";
}
return 0;
}
啊,原来的问题已经更新...... OMG
然后,下一步
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
int
main(int argc, char* argv[]) {
std::ifstream file1("file1.csv");
std::ifstream file2("file2.csv");
std::ofstream out("final.csv", std::ios::app);
std::string buf1;
std::string buf2;
while(file1 >> buf1) {
file2 >> buf2;
out << buf1 << " " << buf2 << std::endl;
}
file1.close();
file2.close();
out.close();
}
答案 2 :(得分:0)
std::ifstream file1("file1.csv");
std::ifstream file2("file2.csv");
std::ofstream out("final.csv", std::ios::app);
std::string buf1;
std::string buf2;
while(file1 >> buf1) {
file2 >> buf2;
out << buf1 << " " << buf2 <<std::endl;
}
file1.close();
file2.close();
out.close();
QFile file11("fil.csv");
file11.open(QIODevice::ReadOnly | QIODevice::Text);
QFile file22("final.csv");
file22.open(QIODevice::ReadOnly | QIODevice::Text);
QFile res("finally.csv");
res.open(QIODevice::WriteOnly);
QTextStream stream;
stream.setDevice(&res);
while (file11.atEnd() == false && file22.atEnd() == false)
{
QByteArray s1 = file11.readLine();
if (s1.endsWith("\n"))
{
s1.chop(1);
}
QByteArray s2 = file22.readLine();
if (s2.endsWith("\n"))
{
s2.chop(1);
}
stream << s2 << " " << s1 << "\n";
}
file11.close();
file22.close();
res.close();