2016-07-17 92 views
-3

這是一個家庭工作問題,所以如果你不是我理解的那些人的粉絲。這裏是我的代碼:C++:無法將輸入文件中的行復制到輸出文件

#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複製到輸出文件中。有人知道我在這裏失蹤了嗎?

+2

誰教你這樣的:'如果(myfile2,行== 「添加」);'? - 它實際上是一個有效的代碼,但它似乎你不知道它在做什麼 – WhiZTiM

+0

老實說,我試圖從我在網上找到的研究和例子。我想我不知道它在做什麼......我認爲它會分析單詞「add」的文件。 – Sammy

+0

你需要停止夢想。這段代碼沒有意義。最好諮詢cppreference並獲取[book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – LogicStuff

回答

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; 
} 
+0

感謝您的幫助!你把我推向更好的方向! – Sammy