Reading from a text file

I am trying to read lines from a text file whose name is passed as a command line argument. I have tried numerous things but have been yet been able to get the file open. I have no compiler issues. The file that I am trying to open is called words.txt and is in the same directory as the cpp. My code is below, thanks for any help.

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
#include <sstream>
#include <iostream>
#include <fstream>
#include "HTable.h"

using namespace std;

int main(int argc, char *argv[])
{

	string temp = argv[1];
	cout << temp << endl;
	
	ifstream WordsIn;
	
	
	WordsIn.open(temp.c_str());
	if(WordsIn.is_open()==false)
	{
		cout << "Could not open list of words\n";
	}
	else
	{
             .....
        }
Are you actually passing it as an argument? Also, if the user doesn't input an argument you will be accessing invalid data, so check argc beforehand. Other then that...I don't see anything that's wrong...
I am passing it as an argument: im using cygwin so once i have compiled the program I run it via ./a words.txt

as for checking for invalid data, i will be sure to do that as soon as i get the code working.
I have just tried to open the file not by doing

ifstream WordsIn ("words.txt");

and even that is failing. Any ideas.
Try adding / before words.txt or ./
Are you sure there is a "words.txt", spelled and capitalized correctly, in the same directory as your executable?

For example:
> ls
a HTable.h Makefile main.cpp words.txt

Your usage is fine:
>./a words.txt


Anyway, I don't use the is_open method but I know that if(WordsIn) is true if the ifstream openned with the ifstream WordsIn("words.txt"); syntax...

Are you sure that it's compiling? Maybe the executable is old... Try:
> rm a
and then make or g++, etc..
Last edited on
the words.txt file is in the same directory and spelled exactly as is in the code, also the executable is current. I have no idea why it won't work because it doesn't seem that complex.
Post more information, if possible. Does it compile and then just output "could not open list of words"?
Yes it compiles without error and then says cannot open list of words
Topic archived. No new replies allowed.