1

Error after compiling in visual studio (C2120: 'void' illegal with all types). New to c++, basically trying to make the program return an error if the file they enter does not exist. Any advice would help. Thanks!

#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
int main()
{
    string input_file_name;
    cout << "Give name of input file : ";
    cin >> input_file_name;
    ifstream ins(input_file_name.c_str());
    assert(ins);

    if (assert(ins) == false)
        cout << "Error: " << input_file_name << "does not exist";
}
klu20
  • 21
  • 5
  • 2
    More to the point, what are you trying to accomplish with `if (assert(ins) == false)` in the first place? I'm pretty sure you're wanting `if (!ins.is_open())`. And fyi, not-exist is only one of the cases where open-for-read can fail; there are others, so that error message is somewhat presumptive. – WhozCraig Feb 15 '20 at 18:50
  • @WhozCraig Yes that was what I was trying to accomplish. If you don't mind what other ways can errors occur? Also when I run the new code the cout error message does not execute. After an error I get an, assertion failed/abort() has been called error. Thank you so much! – klu20 Feb 15 '20 at 19:04
  • There is always the old fashion test: `if (!ins) { /* perform error handling */ }`. There is more than one way that an open can fail. – Thomas Matthews Feb 15 '20 at 19:33

1 Answers1

1

The definition of assert macro is void assert (int expression); as in C++ assert, thus you should not compare its return value.

Additionally, there are some ways you can accomplish some of your goals:

André Caceres
  • 719
  • 4
  • 15