2015-12-30 131 views
0

所以我想從文本文件中讀取。它表明我可以成功從文件中讀取但是當我嘗試關閉值時,它只顯示0,而我在文本文件中有其他值。用ifstream從文本文件中讀取

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


using namespace std; 

int main() 
{ 

    std::ifstream file("numbers.txt"); 
if (file) { 
    cout << "Managed to read file successfully. \n"; 
}else{ 
    cout << "Unable to read file."; 
} 


int x, y; 

file >> x >> y; 

cout << "Num 1: " << x << endl; 
cout << "Num 2: " << y << endl; 

    return 0; 
} 
+1

請顯示文件內容。 – Barmar

+0

當您打印'管理成功讀取文件'時,您沒有從文件中讀取任何內容。你所做的只是打開它。 – Barmar

+0

爲什麼這個問題聽起來如此怪異的像http://stackoverflow.com/questions/34489267/how-to-read-data-from-files-in-turbo-c-4-0和http://stackoverflow.com/questions/34486953/how-to-read-numbers-on-text-files-using-turbo-c-4-0?現在有線上課了嗎? –

回答

0

上面的代碼將打印作業的狀態,如果你想閱讀和顯示內容的,你必須寫這樣的代碼:

#include<iostream> 
#include<fstream> 

using namespace std;   

int main()  
{ 
      ifstream stream1("D:\\file1.txt");  
      char a[80]; 

      if(!stream1)  
      { 
         cout << "While opening a file an error is encountered" << endl;  
      }  
      else  
      {  
         cout << "File is successfully opened" << endl;  
      } 

      while(!stream1.eof())  
      {  
         stream1 >> a;  
         cout << a << endl;  
      } 

      return(0);  
} 
+1

[爲什麼iostream :: eof內部循環條件被認爲是錯誤的?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Barmar

+0

爲什麼如果他只想讀2個數字,他需要一個循環? – Barmar

0

隨着numbers.txt文件

45 
15 

你的代碼工作找到與gcc。

int main() 
{ 
    std::ifstream file("numbers.txt"); 
    if (file) 
    { 
     cout << "Managed to read file successfully. \n"; 
     int x, y; 
     file >> x >> y; 

     cout << "Num 1: " << x << endl; 
     cout << "Num 2: " << y << endl; 
    } 
    else 
    { 
     cout << "Unable to read file."; 
    } 
    return 0; 
} 
+0

這不是一個答案,也不能解釋他的程序出了什麼問題,或者你是如何解決問題的。它應該是一個評論。當你獲得聲望= 50時,你可以評論其他人的問題。 – Barmar