2012-12-19 48 views
2

我從文件讀取特定數據時遇到一些問題。該文件在第一行和第二行上有80個字符,第三行上有未知數量的字符。以下是我的代碼:如何在C++中讀取由讀取的字符數定義的文件段?

int main(){ 
    ifstream myfile; 
    char strings[80]; 
    myfile.open("test.txt"); 
    /*reads first line of file into strings*/ 
    cout << "Name: " << strings << endl; 
    /*reads second line of file into strings*/ 
    cout << "Address: " << strings << endl; 
    /*reads third line of file into strings*/ 
    cout << "Handphone: " << strings << endl; 
} 

如何在評論中執行操作?

+6

如果要讀取線條,請使用[getline](http://www.cplusplus.com/reference/istream/istream/getline/)。如果你想閱讀一些精確的字節數,使用[閱讀](http://www.cplusplus.com/reference/istream/istream/read/)。 –

+0

並使用'std :: string'來處理第三行。 – nims

+0

現在成千上萬的重複... –

回答

3

char strings[80]只能容納79個字符。做它char strings[81]。如果您使用std::string,則可以完全忽略尺寸。

您可以使用std::getline函數讀取線條。

#include <string> 

std::string strings; 

/*reads first line of file into strings*/ 
std::getline(myfile, strings); 

/*reads second line of file into strings*/ 
std::getline(myfile, strings); 

/*reads third line of file into strings*/ 
std::getline(myfile, strings); 

上面的代碼忽略的信息,第一和第二行是80個字符長(我假設你正在閱讀基於行的文件格式)。如果重要,您可以添加額外的支票。

+0

但是,當我顯示添加cout << strings << endl; 它什麼也沒有顯示,我接下來會做什麼? – Deckdyl

+0

也許文件未找到或內容無效。每次操作後,使用'if(!myfile)cout <<「File error」<< endl;'檢查錯誤,包括'myfile.open'。 – Alex

+0

好的,在原始代碼中發現問題...我的文件路徑錯了。謝謝你的幫助。 – Deckdyl

1

在你的情況下,使用字符串而不是char []會更合適。

#include <string> 
using namespace std; 

int main(){ 
    ifstream myfile; 
    //char strings[80]; 
    string strings; 
    myfile.open("test.txt"); 

    /*reads first line of file into strings*/ 
    getline(myfile, strings); 
    cout << "Name: " << strings << endl; 
    /*reads second line of file into strings*/ 
    getline(myfile, strings); 
    cout << "Address: " << strings << endl; 
    /*reads third line of file into strings*/ 
    getline(myfile, strings); 
    cout << "Handphone: " << strings << endl; 
} 
+0

好的,非常感謝。 – Deckdyl

相關問題