2015-12-30 128 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