2016-12-16 15 views
1

我有一個包含例如TXT文件:我使用ifstream :: fail()方法的方式不好嗎?

Arthur 20 

Mark 21 

Josh 12 

的是之間,其僅適用於可讀性沒有空的車道!

我想要做的就是把它寫在屏幕上,就像它在文件中一樣。

我試圖讓這種方式:

ifstream file; 
string word; 

file.open("data.txt"); 
while(!file.eof()){ 

    file >> word; 

    if(file.fail()) 
    break; 

    cout << word << " "; 
    file >> word; 
    cout << word << endl; 
} 

但輸出是:

Arthur 20 

Mark 21 

Josh 12 

0 

那麼,爲什麼這個0被抓的空行到我的字符串變量?我認爲失敗()應該停止循環,給我留下正確的輸出?

+0

相關[?爲什麼是的iostream :: EOF算錯了一個循環條件中(http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-一個循環條件考慮錯誤) – Borgleader

+0

此外,你的循環條件是檢查'數據',但你從'文件'讀? – Borgleader

+0

data.txt只是由數據變量處理的文本文件的名稱。 – Slajni

回答

0

只要你有不包含空格和年齡的整數的名字,那麼你可以將name作爲字符串和年齡作爲整數讀取。

你不需要檢查文件是否被成功打開與否你可以簡寫操作:

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


int main() 
{ 

    std::ifstream file; 
    std::string word; 
    int age; 

    file.open("data.txt"); 

    while(file >> word) 
    { 
     file >> age; 
     std::cout << word << " " << age << std::endl; 
    } 


    std::cout << std::endl; 
    return 0; 
} 
  • ,如果你想使用一個變量

    而且可以肯定的字符串之一,那麼:

    while(file >> word) 
    { 
        std::cout << word << " "; 
        file >> word; 
        std::cout << word << std::endl; 
    } 
    

我看不出有什麼好東西來讀年齡爲一個字符串,也許以後它轉換爲整數!

輸出:

Arthur 20 
Mark 21 
Josh 12 
相關問題