2017-06-04 46 views
-2

我正在學習如何使用c plus plus讀取/寫入文件,並遇到了複製txt文件第一行的問題。我粘貼下面的txt文件。正如你所看到的,第一行有兩個字符串,而下面的行是不同的類型。我如何聲明第2列的類型,因爲它是第1行的一個字符串,之後是整數?雖然我可以通過將所有內容聲明爲字符串來將文件的內容複製到output.txt,但我很好奇如何處理不同的類型。非常感謝您的幫助。C plus plus不同類型的I/O副本txt文件

input.txt文件:

firstname value 
Jack 1 
Jacob 3 
Jerry 2 
Jeremy 3 
Joseph 3 
Jim 3 

我正因爲衝突類型的空白output.txt文件,我認爲。

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

string fname; 
int value; 

using namespace std; 

int main() { 
    ifstream in_file; //variable name 
    in_file.open("input.txt"); 
    if (in_file.fail()){ 
     cout << " The file is not found " << endl; 
     return 1; 
    } 


    ofstream out_file; 
    out_file.open("output.txt"); 
    while (in_file >> fname >> value){ 
    out_file << fname << " " << value << endl; 
    }; 


} 
+1

剛剛處理的第一行以不同的方式,爲兩個字符串,不是一個字符串和一個int。 – ForceBru

回答

0

感謝@ForceBru這爲我工作,但請讓我知道是否有做到這一點更有效的方式:

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

string fname; 
string col2; 
int lname; 

using namespace std; 

int main() { 
    int count=0; 
    ifstream in_file; //variable name 
    in_file.open("input.txt"); 
    if (in_file.fail()){ 
     cout << " The file is not found " << endl; 
     return 1; 
    } 


    ofstream out_file; 
    out_file.open("output.txt"); 

    if (count==0){ 
     in_file >> fname >> col2; 
     out_file << fname << " " << col2 << endl; 
     count++; 
    } 

    while (in_file >> fname >> lname){ 
     out_file << fname << " " << lname << endl; 
    }; 



} 
+0

爲什麼你需要爲第一行計數?你也不需要這些值,一個簡單的getline就會跳過它們。 – 2017-06-04 18:01:02

+0

計數是用於指定第一行的字符串值,我不知道如何實現getline – st4rgut

+0

@st以及count如何知道,這是第一行?你應該使用getline,而不是實現它。 – 2017-06-07 09:17:52