2011-04-20 71 views
2
int test = 0; 
ifstream inFile; 
inFile.open("hat.txt"); 
inFile >> test; 
cout << test; 

我在调试文件夹中运行.exe文件,该文件的文件是hat.txt。它只有一个数字。我的问题是为什么我输出时会变得垃圾?垃圾简单读取

编辑 - 添加失败线,它确实失败。为什么失败?


int test; 
ifstream inFile; 
inFile.open("hat.txt"); 
if (inFile.fail()) 
{ 
    cout << "It Failed" << endl; 
} 
inFile >> test; 
cout << test; 
+1

是在正确的位置hat.txt? – 2011-04-20 22:27:00

回答

2

您的代码现在看起来没问题,因为它检查失败。

它为什么失败?可能该文件不存在或者权限错误。

我跑这个代码。

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    int test; 
    std::ifstream inFile; 
    inFile.open("hat.txt"); 
    if (inFile.fail()) 
    { 
     cout << "It Failed" << endl; 
    } 
    inFile >> test; 
    cout << test; 
      return 0; 
} 

它工作正常。如果hat.txt不存在或不能被读取,那么我得到“它失败”。没有失败的支票,我得到随机数字输出。

我认为你的问题是它无法读取文件。

1

有一个号码后最终的行?已知这会导致某些工具集出现问题。

0

调试文件夹(您说hat.txt驻留的地方)也是您的工作目录吗?
是否以任何方式锁定了hat.txt(例如,在应用程序中打开)?

0

看起来像默认情况下,您使用read或getline将文本读入字符串。您可以使用ios :: binary标志将ifstream更改为二进制。然后你可以设置一个缓冲区并读入。然后您需要转换为文本输出。