这是一个家庭工作问题,所以如果你不是那些我理解的粉丝。这是我的代码:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
fstream myfile1("datafile1.txt"); //this just has a bunch of names in it
fstream myfile2("cmdfile1.txt"); //has commands like "add bobby bilbums"
ofstream outputFile("outfile1.txt"); //I want to take the "add bobby" command and copy the name into this new file.
string line;
if (myfile1.is_open() && myfile2.is_open()) //so I open both files
{
if (myfile2, line == "add"); //If myfile2 has an "add" in it
{
outputFile.is_open(); //open outputfile
outputFile << line << endl; //input the line with add in it till the end of that line.
}
}
cout << "\nPress Enter..."; // press enter and then everything closes out.
cin.ignore();
outputFile.close();
myfile2.close();
myfile1.close();
return 0;
}
问题是,虽然outputFile总是为空。它永远不会将cmdfile1中的任何行复制到输出文件中。有谁知道我在这里缺少什么?
答案 0 :(得分:0)
尝试更像这样的东西:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream myfile1("datafile1.txt");
ifstream myfile2("cmdfile1.txt");
ofstream outputFile("outfile1.txt");
string line;
if (/*myfile1.is_open() &&*/ myfile2.is_open() && outputFile.is_open())
{
while (getline(myfile2, line))
{
if (line.compare(0, 4, "add ") == 0)
{
outputFile << line.substr(4) << endl;
}
}
}
myfile1.close();
myfile2.close();
outputFile.close();
cout << "\nPress Enter...";
cin.ignore();
return 0;
}