开发者

Garbage from a simple read

开发者 https://www.devze.com 2023-02-27 22:36 出处:网络
int test = 0; ifstream inFile; inFile.open(\"hat.txt\"); inFile >> test; cout << te开发者_JAVA百科st;
int test = 0;
ifstream inFile;
inFile.open("hat.txt");
inFile >> test;
cout << te开发者_JAVA百科st;

I have the file in the debug folder where the .exe is running and the file of that file is hat.txt. All it has is one number. My question is why am I getting junk when I output ?

EDIT - Added the fail line and it does fail. Why is it failing?


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


Your code looks fine now that it has the failed check.

Why did it fail? probably the file doesn't exist or has the wrong permissions.

I ran this code.

#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;
}

And it works fine. If hat.txt doesn't exist or can't be read then I get "It failed". Without the failed check, I get random numbers outputed.

I think you're problem is that it can't read the file.


Is there an end-of-line after the one number? This has been known to cause problems with certain toolsets.


Is the debug folder (where you say hat.txt resides) also your working directory?
Is hat.txt locked in any way (e.g. open in an application)?


Looks like by default you read in text using read or getline into a string. You can change the ifstream to binary using the ios::binary flag. you can then setup a buffer and just read into that. You would then need to convert for outputting as text.

0

精彩评论

暂无评论...
验证码 换一张
取 消