2017-02-21 83 views
1

從文件讀取我有一個看起來像一個文件:使用函數getline C++

Sister Act 
Whoopi GoldBerg 
Maggie Smith 
Schwartz 
Ardolino 
Touch Stone Pictures 
14 

我無法讀取信息,並將其保存到一個對象。我沒有收到任何錯誤,但我無法使程序正確讀取信息。

我的問題是任何人都可以告訴我需要更改哪些內容才能讓我的程序正確讀取文件。

而且每行可以有除了整數多個單詞和空白行7

string title, starName1, 
    starName2, producer, 
    director, prodCo; 
int numCopies; 
ifstream videoFile("videoDat.txt"); 

if (videoFile.is_open()) { 
    getline(videoFile, title); 
    getline(videoFile, starName1); 
    getline(videoFile, starName2); 
    getline(videoFile, producer); 
    getline(videoFile, director); 
    getline(videoFile, prodCo); 
    //getline(videoFile, numCopies); //compiler error 

    while (videoFile >> title >> starName1 >> starName2 >> producer >> director >> prodCo >> numCopies) { 
     //be able to do stuff with variables individually 
    } 
} 

我想我需要做的是這樣的:

while (getline(videoFile, title) && getline(videoFile, starName1) && getline(videoFile, starName2) 
     && getline(videoFile, producer) && getline(videoFile, director) && getline(videoFile, prodCo) && videoFile >> numCopies) { 
     //be able to do stuff with variables individually 
    } 
+0

請提供[MCVE(http://stackoverflow.com/help/mcve),這是很難推理編譯和正確性錯誤時,也有很多的片斷用戶定義類型。 – yeputons

+0

我試圖編輯只留下給我沒有用戶定義類型的問題的代碼。 – Asuu

回答

2
getline(videoFile, numCopies); //numCopies should not be an int, but a str. 

numCopies是一個int。這樣做:

string numCopiesStr; 

getline(videoFile, numCopiesStr); 
int numCopies = std::stoi(numCopiesStr); 

這應該工作。

的另一種方式,但錯誤處理變得棘手,是使用std :: CIN:

std::cin >> numCopies; 

將讀取的INT入變量numCopies但究竟會停在那裏,在那之後,沒有得到全線。

您不能使用操作符>>讀取由空格分隔的字符串,它會停在第一個空格處。你需要getline。

我的建議是你使用一個字符串numCopiesStr並在每個迭代的循環內轉換爲int。

如果您可以更改輸入文件的格式(向Sister Act添加引號,例如「Sister Act」等),另一個解決方案(自C++ 14以來)將使用std::quoted修飾符。在這種情況下,你可以直接使用int爲numCopies和做到這一點,只要你引用的每個字符串,而不是數字:

while (std::quoted(videoFile) >> std::quoted(title) ... >> numCopies) { 
} 

瞭解如何在這裏使用std::quotedhttp://en.cppreference.com/w/cpp/io/manip/quoted

啊,並保持您的cppreference.com總是接近您,它可以幫助很多;)

+0

這解決了我的問題與一些試驗和錯誤。 Atleast讓我走上了正確的道路,謝謝你。 – Asuu

0

getline(...)的默認行爲是從輸入流中讀取並將其存儲在一個字符串中。在這裏檢查。 http://en.cppreference.com/w/cpp/string/basic_string/getline

因此,你將不得不做任何字符串到int轉換技術來讀取使用getline並將其轉換爲int。

建議:對於從字符串轉換爲int,取決於性能和準確性,您可以查看:boost :: coerce或boost :: lexical cast或sscanf或stoi。檢查: Alternative to boost::lexical_cast

0

我知道我有用戶定義的數據類型在這裏,但這是我做了什麼來解決這個問題。我在while循環中以字符串的形式讀取它,然後使用stoi將其轉換爲整數。感謝所有的幫助!

 while (getline(videoFile, title) && getline(videoFile, starName1) 
     && getline(videoFile, starName2) && getline(videoFile, producer) 
     && getline(videoFile, director) && getline(videoFile, prodCo) 
     && getline(videoFile, numCopiesStr)) { 
     tempVideo.setVideos(title, starName1, starName2, producer, director, prodCo, stoi(numCopiesStr)); 
     videos.addNodeToTail(tempVideo); 
    } 
}