C++ 当文件无法';不能用c+打开+;,我希望它结束程序,而不是输出更多的东西

C++ 当文件无法';不能用c+打开+;,我希望它结束程序,而不是输出更多的东西,c++,C++,当文件无法在c++中打开时,我希望它结束程序,而不是输出更多的内容 我的代码: #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 /

当文件无法在c++中打开时,我希望它结束程序,而不是输出更多的内容

我的代码:

#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
输出应为:

File "invalidfile.txt" could not be opened
附件输出图片:


一个好方法是使用cstdlib中的exit命令。 基本上,只要抛出错误,也可以调用exit。比如说

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

std::cout那么,如果你想停止执行,有什么问题吗?你也可以抛出一个异常并调用
std::terminate()
@AlgirdasPreidžius我是一个编码的noob,想建议怎么做吗?@FranciscoGallegoSalido在哪里添加terminate()代码?@Jasminjak以任何你想要的方式:异常、返回函数
bool
(作为成功/失败的标志),
std::exit
。如果您只是在学习,我建议您从。
std::cout << "Fatal error: Invalid file" << std::endl;
std::exit(1);