Bartholomew Bartholomew - 2 months ago 22
C++ Question

Error, "Code will never be executed", with output stream

I'm having trouble with this code in Xcode:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ofstream out;
char c;
out.open("call_data.txt");
if (out.fail())
cout << "failed." << endl; exit(1);
cout << "Print something to a file :" << exit(1);//I get the error here
cin >> c;
out << c;
out.close();
return 0;
}


Can someone tell me why I get this error? I can't figure it out. Am I maybe opening the output stream incorrectly? I feel like it has worked before like this.

Answer

With sane formatting your code looks like this:

ofstream out;
char c;
out.open("call_data.txt");
if (out.fail())
   cout << "failed." << endl;
exit(1);
cout << "Print something to a file :" << endl; //exit(1) shouldn't be here either
cin >> c;
out << c;
out.close();

Call to exit will always happen, anything later cannot be reached. Use {} for multi-statement ifs:

if (out.fail()) {
    cout << "failed." << endl;
    exit(1);
}