istream problem, file does not open

My program below compiles and runs, but does not open NumsIn.txt. The input file (NumsIn.txt) has sixtyfour 1's.

Any guidance would be appreciated.

Thanks in advance.

//
// istream::get example
//
#include <cstdio>
#include <cstdlib>
#include <iostream> // std::cin, std::cout
#include <fstream> // std::ifstream
using namespace std;

int main()
{
char str[64];

std::cout << "Enter the name of the exisiting text file: ";
std::cin.get (str,64); // get c-string

std::ifstream is(str); // open file

// Check file is open
if (!"NumsIn.txt") { //check to read in_file
cerr << "Can't open input file " << "NumsIn.txt" << endl;
exit(1);
}

char c;
while (is.get(c)) // loop getting single characters
std::cout << c;

is.close(); // close file

// wait until user is ready before terminating program
// to allow the user to see the program results
system("PAUSE");
return 0;
}
Last edited on
Check file is open - should look like this:
1
2
3
4
5
6
7
    std::ifstream is(str); // open file

    // Check file is open
    if (!is) { 
        cerr << "Can't open input file " << str << endl;
        exit(1);
    }
Thanks Chervil!

After correcting Check-File, it shows the file can not be opened. Why? NumsIn.txt is text file with one's...
Most likely the program is looking in a particular directory for the file, but it is in a different one.
Try placing the file in the same location as the executable program (not necessarily the same as the source code files). Or specify the path as well as file name.
It is in the same directory and actually, it was something even simpler: I omitted the ".txt".

Thank you Chervil for your help and assistance.
Topic archived. No new replies allowed.