Reading from a text file but it won't open!

I'm just using a text file that I made as 'poop.txt'
Wrote random words and tried to open it.
I can't get the file to open..?
Is there something wrong with the code, or does it need to be saved in a certain location on the computer?
Ignore the commented out sections and prototypes!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
#include<vector>
#include<fstream>
#include<string>
using namespace std;
void loadWords();
int sequentialSearch();
void selectionSort();
int binarySearch();


int main()
{
	//"_"(?) == declares a size for a vector
	//"_".size() == shows the size of the working vector
	/*vector<string> words;*/


	loadWords();


	system("pause");
	return 0;
}


void loadWords()
{
	ifstream inFile("poop.txt");
	string s;
	inFile.open("poop.txt");
	//"?".is_open returns true or false checks if file is open
	while (!inFile.eof())
	{
		getline(inFile, s);
		cout << s;
	}
	inFile.close();
}
The file needs to be saved in the same folder as the c++ project. Also, line 31 is not necessary, the file is already opened on line 29.
Last edited on
OP: Read the following links why eof() is considered a bad idea within loops:

http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong
http://stackoverflow.com/questions/5837639/eof-bad-practice

Hence, would suggest:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void loadWords()
{
	ifstream inFile("F:\\test1.txt");//file path on my laptop, edit as required; 	
	string s;

	if (inFile.is_open())
	{
		while(getline(inFile, s))
		{
			cout << s;
		}
	}
	inFile.close();//this is redundant, the ifstream object closes automatically once it goes out of scope;
}

You'd also need to update your code as and when your input file changes, for e.g has non-whitespace delimiters, other data types etc
Topic archived. No new replies allowed.