2015-05-07 33 views
1

我寫了一些代碼在下面。titleauthors的類型是char數組,我不能改變它。當數據從鍵盤輸入時,結果是正常的。顯示讀取txt文件異常

void BookException::getBook() 
{ 
    cout<<"Id number: "; 
    cin>>booknum; 
    cout<<"Title: "; 
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    cin.getline(title, sizeof(title), '\n'); 
    cout<<"Authors: "; 
    cin.getline(authors, sizeof(authors), '\n'); 
    cout<<"Number of pages:"; 
    cin>>pagenum; 
    cout<<"Price: "; 
    cin>>price; 
    cout<<"over"<<endl; 
} 

這裏是低於

1 
How to program C++ 
Paul Deitel, Harvey Deitel 
1028 
112.83 

輸入文本但是,當我嘗試讀取從一個txt file.It一些文字displaied這樣的:

Id number: Title: Authors: Number of pages:Price: The no. 0 book error. Title: Authors: Number of pages: 0 Price: 0.00 Incorrect price. 我認爲getline由於問題,但我不知道如何解決它。謝謝。

回答

1

我沒有看到文件被傳入或在您的代碼中打開。在閱讀它們或換行符後,你也不會打印任何變量。使用字符串會容易得多,但是如果你必須使用char數組,我會建議編寫一個函數來從c字符串轉換爲字符串,並返回,參見:c_str()

void BookException::getBook() { 

    string booknum, title, authors, pagenum, price; 
    ifstream fin;   //file in 
    fin.open("book.txt"); //Open the file 


    getline(fin, booknum); //Read line from file first 
    cout << "Id number: " << booknum << endl; //Then print 
    getline(fin, title); 
    cout << "Title: " << title << endl; 
    getline(fin, authors); 
    cout << "Authors: " << authors << endl; 
    getline(fin, pagenum); 
    cout << "Number of pages:" << pagenum << endl; 
    getline(fin, price); 
    cout << "Price: " << price << endl; 
    cout << "over" << endl; 

    fin.close(); //Close the file 
} 

我建議閱讀這一點,除非你明白這一切:input/output with files

getline()使用可以發現here