-1

when file couldn't be opened in c++, I want it to end the program, and not output more stuff!

my code:

#include<iostream>
#include <fstream>
#include<stdlib.h>
using namespace std;

// Function to accept a file names from the user and read file contents
// First Parameter: Student Answer file
// Second Parameter: Correct Answer file
// Third Parameter: Character type array to store student answers
// Fourth Parameter: Character type array to store correct answers
void readFile(string fileStuAns, string fileCorrAnswer, char sAns[], char           cAns[])
{
    // Initialize the line counter to zero
    int counter = 0;
    // Creates ifstream class objects
    ifstream inSFile, inCFile;
    // Opens the file for reading data from text file student answer
    inSFile.open (fileStuAns.c_str());
    // Opens the file for reading data from text file for correct answer
    inCFile.open (fileCorrAnswer.c_str());
    // Checks if student answer file can be opened or not
    if(inSFile.fail())
    {
        // Displays error message
        cout<<"File "<<"\""<<fileStuAns<<"\""<< " could not be opened"<<endl;
        return;
    }// End of if condition
     // Checks if file can be opened or not
    if(inCFile.fail())
    {
        // Displays error message
        cout<<"File "<<"\""<<fileCorrAnswer<<"\""<< " could not be opened";
        return;
    }// End of if condition
     // Loops till end of the student answer file
    while(!inSFile.eof())
    {
        // Reads data from file and stores student answer character array's counter      index position
        inSFile>>sAns[counter];
        // Increase the current line counter by one
        counter++;
    }// End of while
     //Close student answer file
    inSFile.close();
    // Reset the counter to zero
    counter = 0;
    // Loops till end of correct answer the file
    while(!inCFile.eof())
    {
        // Reads data from file and stores correct answer character array's counter      index position
        inCFile>>cAns[counter];
        // Increase the current line counter by one
        counter++;
    }// End of while

     // Close correct answer file
    inCFile.close();
}// End of function

// Displays the student result
// First Parameter: Character type array contains student answers
// Second Parameter: Character type array contains correct answers
void resultSheet(char sAns[], char cAns[])
{
    // Displays student answers
}// End of function

// Function to write data to file entered by the user
// First Parameter: Invalid Answer file
// Second Parameter: Character type array contains student answers
// Third Parameter: Character type array contains correct answers
void writeTextFile(string fileInAnschar, char sAns[], char cAns[])
{
    // To store number of lines
    int cA, iA;
    cA = iA = 0;
    // ofstream class object created
    ofstream outFile;
    // Opens the file for writing onto a text file
    outFile.open(fileInAnschar.c_str());
    // Checks if file can be opened or not
    if(outFile.fail())
    {
        // Displays error message
        cout<<"\n Error: Unable to open "<<fileInAnschar;
        return;
    }// End of if condition
     // Loops till 20 times for 20 questions

    for(int c = 0; c < 20; c++)
    {
        // If student answers current index position value is not equals to correct      answer's current index position
        if(sAns[c] != cAns[c])
        {
            // Writes the result to the file
            outFile<<"Question "<<(c + 1)<<" has incorrect answer "<<"'"<<sAns[c]<<"'" <<", the correct answer is "<<"'"<<cAns[c]<<"'"<<endl;
            // Displays the result
            cout<<"Question "<<(c+1)<<" has incorrect answer "<<"'"<<sAns[c]<<"'"<<",      the correct answer is "<<"'"<<cAns[c]<<"'"<<endl;
            // Increase the counter by one
            iA++;
        }// End of if condition
    }// End of for loop
     // Calculates number of correct answers
    cA = 20 - iA;
    // Calculates the average
    double percent = cA / 20;
    // Checks if the average is greater than or equals 70
    if(iA <= 6)
    {
        // Displays the result
        cout<<iA<<" questions were missed"<<endl;
        cout<<"The student passed"<<endl;
    }// End of if condition
     // Otherwise fail
    else
    {
        cout<<iA<<" questions were missed"<<endl;
        cout<<"The student failed"<<endl;
    }// End of else
     //Close file
    outFile.close();
}//End of function

// main function definition
int main()
{
    // Character array to store student answers
    char studentAnswer[21];
    // Character array to store correct answers
    char correctAnswer[21];
    // To store the file name
    string fileNameStu, fileNameCorr;
    // Accepts the file name to read

    cin>>fileNameStu;

    cin>>fileNameCorr;
    // Calls the file to read student answer and correct answer and stores it in respective arrays
    readFile(fileNameStu, fileNameCorr, studentAnswer, correctAnswer);
    // Calls the function to display student answer and correct answer
    resultSheet(studentAnswer, correctAnswer);
    // Accepts the file name to write invalid answers

    cin>>fileNameStu;
    // Calls the function to write invalid answers
    writeTextFile(fileNameStu, studentAnswer, correctAnswer);
}// End of main function

My output:

File "invalidfile.txt" could not be opened

b"Question 1 has incorrect answer '\xf0', the correct answer is '\x00'\nQuestion 2 has incorrect answer ';', the correct answer is '\x00'\nQuestion 3 has incorrect answer '\xae', the correct answer is '\x00'\nQuestion 4 has incorrect answer '\xa7', the correct answer is '\x00'\nQuestion 5 has incorrect answer '\xff', the correct answer is '\x00'\nQuestion 6 has incorrect answer '\x7f', the correct answer is '\x00'\n"Question 9 has incorrect answer 'T', the correct answer is ''
Question 10 has incorrect answer '', the correct answer is ''
Question 11 has incorrect answer '@', the correct answer is ''
Question 17 has incorrect answer '', the correct answer is 'p'
Question 18 has incorrect answer '', the correct answer is ''
Question 19 has incorrect answer '', the correct answer is '@'

12 questions were missed

The student failed

Output should be:

File "invalidfile.txt" could not be opened

Attached picture of output:

enter image description here

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

1

A good way to do this is to use the exit command that is in cstdlib. Basically anytime you throw an error also call exit. For example

std::cout << "Fatal error: Invalid file" << std::endl;
std::exit(1);

exit will terminate the program and by passing the '1' argument, it will terminate "unsuccessfully"

Adam Snaider
  • 188
  • 1
  • 8