你好,我有一个小问题,我试图从一个文件加载到另一个文件。问题是:幼稚包含图形:something图: something2等等。我只需要加载那个图:和图形:),但是在第二个文件中不能写图形:只有的东西。
后来我需要计算一个图的成分,我已经有了计算图的成分的功能,但是我只需要加载一个图,写一个组件,然后清除它,加载第二个,等等。我在那个文件中有9个图。知道怎么做吗?这是我的代码:
void load2()
{
ifstream infile;
infile.open("graph.txt"); //input file
ofstream outfile;
outfile.open("out.txt"); //output file
while (!infile.eof()) {
char c = infile.get();
if (c == 'g') {
break;
}
while (!infile.eof()) {
char c = infile.get();
if (c == 'g') {
for (int i = 0; i < 6; i++) { //delete 6 characters include g (graph)
infile >> c;
}
}
outfile << c;
}
}
infile.close();
outfile.close();
}发布于 2014-04-22 01:00:36
假设graph:和something用空格分隔
void load2()
{
ifstream infile("graph.txt");
ofstream outfile("out.txt");
std::string graph, something;
while (infile >> graph >> something) {
if (graph != "graph:") {
break;
}
outfile << something;
}
}下面应该处理您的评论中所解释的格式
std::string token;
while (infile >> token) {
if (token != "graph:") {
outfile << token;
}
}发布于 2014-04-22 02:16:01
下面是我如何使用C++11来完成这个任务:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
const std::string target{"graph:"};
if (argc < 2) {
std::cout << "Usage: graph filename\n";
return 0;
}
std::string line;
std::size_t t1;
std::size_t t2;
std::string output;
std::vector<std::string> answers;
bool emitting = false;
for (std::ifstream in(argv[1]); std::getline(in, line); ) {
t1 = 0;
for (t2=line.find(target); t2 != std::string::npos;
t2 = line.find(target,t1))
{
if (emitting) {
output += line.substr(t1,t2-t1);
answers.push_back(output);
output.clear();
// emitting = false;
} else {
emitting = true;
}
t1 = t2+target.size();
}
if (emitting) {
output += line.substr(t1);
output += '\n';
}
}
for (const auto &s : answers)
std::cout << "[" << s << "]";
std::cout << '\n';
}如果您的文件内容是:
graph: Q R J A graph: P L L A graph: A B C D graph:此程序将打印:
[ Q R J A ][ P L L A ][ A B C D ]如果您打算只在图的匹配对之间打印:令牌,请取消注释输出行,然后它将打印出来。
[ Q R J A ][ A B C D ]https://stackoverflow.com/questions/23208480
复制相似问题