int main()
{
using namespace std;
ifstream in_stream;
ofstream out_stream;
in_stream.open("C:\Documents and Settings\Administrator\Desktop\HW\HW4\hw4pr2input.txt");
if (in_stream.fail())
{
cout << "Input file opening failed.\n";
system ("pause");
exit(1);
}
out_stream.open("hw4pr2input_output");
if (out_stream.fail())
{
cout << "Output file opening failed.\n";
system ("pause");
exit(1);
}
int first, second, third;
in_stream >> first >> second >> third;
out_stream << "the sume of the first 3\n"
<< "numbers in the input\n"
<< "is" << (first + second + third)
<< endl;
in_stream.close( );
out_stream.close( );
return 0;
}
#include <iostream>
#include <fstream>
usingnamespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
We understand that much, but you have provided very little information.
Presuming you have checked that
(1) The file path is correct
(2) All \s are written as \\
(3) There are no non-ASCII characters in the filename or anything else that is messing with it
(4) The file does, in fact, exist before the program runs
Then I think you ought to check the file permissions. Does your program have access rights to open a file on your desktop? Does another process have the file opened or locked in some way?
I just tried a primitive cutdown version of this code, it worked fine for me. It may or may not be the answer for you but add
1 2 3 4
if (in_stream.fail() == true)
{
cout << "Fail";
}
I know .fail() returns a bool value, but I am checking it against one anyway to see if it is right or not.
I if \\ fails try using / I am not sure if that will work, but whenever I make programs that deal with files I build them then run the file from the debug/release folder.
while your code is valid Drakon, there are shortcuts that do the samething that make it easier to read. because every condition is resolved to either true (and thusly will execute) or false (and the code will be skipped). so you could actually do if(in_stream.fail()) which is the same as your condition. lets say you wanted to test if it returned false (ie in_stream.fail() == false) that can be short cutted to if(!in_stream.fail()).
lets say you wanted to test if it returned false (ie in_stream.fail() == false) that can be short cutted to if(!in_stream.fail()).
I knew of this method, and I like the smallness of it, but I have to ague for my eyesight I nearly missed the "!'' at the start of your code, thus why I tend to do things the "long" way.
But now I will try when I am explaining code give more than the way I do it.
oh no if thats your way thats fine. if you cant see it (and maybe its just this text not saying you have bad eyesight) then you can write it that way. its just good to know for when you have long conditions