2017-03-02 89 views
1

我想讀取一個文件,其中第一行是一個整數,並且下一行是一個字符串(我必須將其讀入char數組)。 我在輸入流對象上使用了>>運算符來讀取整數,然後我使用.get()方法和.ignore()方法將下一行讀入char數組,但是當我嘗試讀入字符數組我得到一個空字符串 我不知道爲什麼我得到一個空白字符串,你知道爲什麼這可能是?從C++中讀取文件的麻煩

這裏是我使用從文件中讀取的代碼:

BookList::BookList() 
{ 
    //Read in inventory.txt and initialize the booklist 
    ifstream invStream("inventory.txt", ifstream::in); 
    int lineIdx = 0; 
    int bookIdx = 0; 
    bool firstLineNotRead = true; 

    while (invStream.good()) { 
     if (firstLineNotRead) { 
      invStream >> listSize; 
      firstLineNotRead = false; 
      bookList = new Book *[listSize]; 
      for (int i = 0; i < listSize; i++) { 
       bookList[i] = new Book(); 
      } 

     } else { 
      if (lineIdx % 3 == 0) { 
       char tempTitle[200]; 
       invStream.get(tempTitle, 200, '\n'); 
       invStream.ignore(200, '\n'); 
       bookList[bookIdx] = new Book(); 
       bookList[bookIdx]->setTitle(tempTitle); 
      } else if (lineIdx % 3 == 1) { 
       int bookCnt; 
       invStream >> bookCnt; 
       bookList[bookIdx]->changeCount(bookCnt); 
      } else if (lineIdx % 3 == 2) { 
       float price; 
       invStream >> price; 
       bookList[bookIdx]->setPrice(price); 
       bookIdx++; 
      } 
      lineIdx++; 
     } 
    } 
} 

所以LISTSIZE是從該文件的第一行讀取的第一整數,tempTitle是用於讀取的臨時緩衝器在文件第二行的字符串中。但是當我做invStream.get()和invStream.ignore()時,我看到tempTitle字符串是空的。爲什麼?

+2

想想第一個'\ N'按照您在第一行的整數。 –

+0

提供樣本文件? – everettjf

+0

爲什麼不使用'getline()'? –

回答

1

你可以最有可能通過交換線路修復程序

invStream.get(tempTitle, 200, '\n'); 
invStream.ignore(200, '\n'); 

即使用:

invStream.ignore(200, '\n'); 
invStream.get(tempTitle, 200, '\n'); 

作爲一般原則,如果一個文件的內容格式,使得線文本具有特定含義,您將更容易逐行讀取文件的內容並處理每行的內容。

std::string line; 
while (getline(invStream, line)) { 

    if (firstLineNotRead) { 
     // Extract the listSize from the first line using 
     // a istringstream. 
     std::istringstream str(line); 
     str >> listSize; 
     firstLineNotRead = false; 
     bookList = new Book *[listSize]; 
     for (int i = 0; i < listSize; i++) { 
     bookList[i] = new Book(); 
     } 
    } 

    else { 
     // The line has already been read. 
     // Use it. 

     ... 

    } 
} 
3

從文件讀入第一個整​​數後,等待讀取的文件中有一個換行符。

然後繼續告訴它讀取一個字符串。它這樣做 - 將新行解釋爲字符串的結尾,所以您讀取的字符串是空的。在這之後,一切都變得不可思議了,所以其餘的閱讀都保證不成功(至少不能達到你想要的)。

順便說一句,我會去這樣的任務而不同 - 可能更是這樣的:

#include <iostream> 
#include <vector> 
#include <bitset> 
#include <string> 
#include <conio.h> 

class Book { 
    std::string title; 
    int count; 
    float price; 
public: 

    friend std::istream &operator>>(std::istream &is, Book &b) { 
     std::getline(is, title); 
     is >> count; 
     is >> price; 
     is.ignore(100, '\n'); 
     return is; 
    } 
}; 

int main() { 
    int count; 

    std::ifstream invStream("inventory.txt"); 

    invStream >> count; 
    invStream.ignore(200, '\n'); 

    std::vector<Book> books; 

    Book temp; 

    for (int i = 0; i<count && invStream >> temp;) 
     books.push_back(temp); 
}