Hello, I'm trying to have my program read a txt file that's in the same directory as the exe in visual basic. All I get is a blank screen when I run the program (blank black console screen). The program compiles and and runs, but it displays nothing. It should output the first letter, then the next, until the end of the txt file. At least, that's what I want it to do.
#include "stdafx.h"
#include "fstream"
#include "iostream"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile;
infile.open("p4in.txt");
while(!infile.eof())
{
char c = infile.get();
cout << c << endl;
}
}
Looking at your code, it seems that you haven't done any interactions with the file before entering your loop. In order for your loop to work, you'll need to have at least one interaction with the file so that the end-of-file bit is properly set.
So you'd need to alter your code to something like this:
#include "stdafx.h"
#include "fstream"
#include "iostream"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile;
infile.open("p4in.txt");
char c = infile.get();
while(!infile.eof())
{
cout << c << endl;
c = infile.get();
}
}
This way, if there are no more characters in your file, the infile.get() would set off the end-of-file bit, and end the loop in the next iteration.
#include <fstream>
#include <iostream>
usingnamespace std;
int main(int argc, char * argv[])
{
ifstream infile;
infile.open("p4in.txt");
if (!infile.good())
{
cout << "Input file not open" << endl;
return 0;
}
char c = infile.get();
while(!infile.eof())
{
// cout << c << endl;
cout << c;
c = infile.get();
}
return 0;
}
You need to check that the file was successfully opened.
Secondly, doing this is a bad idea:
1 2
char c = infile.get();
cout << c << endl;
Here the second line will attempt to display character c regardless of whether or not the read was successful. My code above makes sure the eof() test is always done before the cout statement is attempted.
Edit: I see that mukomo has said much the same thing.
I don't think I'm actually opening the file. I have the program open in visual studio 2012. The text file is in the same folder as the .sln. This doesn't show anything.
Most likely the file "p4in.txt" is in a different location to the executable program.
My compiler uses separate folders for the release and debugging versions of the program, so some care is needed.]
You need to either place the file in the same folder as the .exe, or specify the full path to the file, for example "c:\\temp\\p4in.txt".
Well, there is another solution, using relative paths, in order to use that, you'd need to know where the .exe resides relative to the .txt file. Then you might use something like "..\\..\\p4in.txt", where .. means one level higher in the folder hierarchy.
Ok, I pasted it in every folder and subfolder in the directory of the program and it appears to have worked. I'll have to figure out the specifics later. Thanks