2012-08-30 53 views
1

我可以使用getline()來使用cin(getline(cin,line)),但是當我打開一個流時,它不會從文件中讀取行。該文件包含元素週期表中的元素列表。C++;使用字符串getline()不能與文件輸入一起工作

例如:
^ h

Ø
等等

編輯:

然而,當我嘗試cout的新線讀取,它不會把它進入var符號的行:
cout < <「symbol:」< < symbol < < endl;

它不給我任何東西,但它應該返回第一個元素(H)。

#include <fstream> 
#include <iostream> 
#include <vector> 
#include <string> 

using namespace std; 

void print(vector <string> x) 
{ 
    cout << "list of elements:" << endl; 
    for (int i = 0; i < x.size(); ++i) 
    { 
     cout << x[i] << endl; 
    } 
} 

int main(int argc, char** argv) 
{ 
    string symbol; 
    vector <string> elementlist; 
    ifstream readin; 

    readin.open("Elements.txt"); 
    getline(readin,symbol); 
    cout << "symbol: " << symbol << endl; 
    while (!readin.good()) 
    { 
     elementlist.push_back(symbol); 
     getline(readin,symbol); 
    } 
    print (elementlist); 
    return 0; 
} 
+3

你能告訴你的代碼? – oldrinb

+0

我在完成我的帖子之前意外打開了輸入。我道歉。 – Cerealkiller050

+1

@ user1634904你的循環條件是'!readin.good()',它最終是'false',所以你永遠不會讀任何東西。反轉它。 – oldrinb

回答

1

我會做這樣的事情:

#include <string> 
#include <iostream> 
#include <fstream> 
#include <vector> 
#include <iterator> 

class line { 
    std::string data; 
public: 
    friend std::istream &operator>>(std::istream &is, line &l) { 
     std::getline(is, l.data); 
     return is; 
    } 
    operator std::string() const { return data; }  
}; 

int main() { 
    std::ifstream readin("Elements.txt"); 

    // Initialize vector from data in stream: 
    // 
    std::vector<std::string> 
     element_list((std::istream_iterator<line>(readin)), 
         std::istream_iterator<line>()); 

    // write data from vector to cout: 
    // 
    std::copy(element_list.begin(), element_list.end(), 
      std::ostream_iterator<std::string>(std::cout, "\n")); 

    return 0; 
}        
+0

難道你不希望'std :: istream_iterator'可以使用自定義分隔符嗎? :-( – oldrinb

+0

@veer:是的,有的時候,並且[盡力](http://stackoverflow.com/a/10060244/179910),它可以。至少對於這個,'line'類更容易。 –

1

正如我在my comment中所述,您的循環條件是錯誤的。

while (!readin.good()) 
{ 
    elementlist.push_back(symbol); 
    getline(readin,symbol); 
} 

事實證明,你循環使用條件readin.good()。由於!readin.good()將評估爲false,因此您從未實際進入循環。

+1

你通常不*要使用'while(x.good())'。前段時間,我發佈了一篇關於如何做到這一點的[博客條目](http://coderscentral.blogspot.com/2011/03/reading-files.html),這可能會有所幫助。 –

+0

@JerryCoffin對。在我最初使用的例子中,我展示了'while(std :: getline(std :: cin,line)&& std :: cin.good()){...}'。那有什麼不對嗎? PS'std :: getline'永遠不會短路。 – oldrinb

+3

是的,'while(std :: getline(...))'通常是做事情的好方法。 –

相關問題