在c ++中终止写操作和关闭文件

时间:2015-11-08 17:05:17

标签: c++

我是C ++的新手。我编写了一个小程序来打开一个文件并用来自用户的输入写入。我需要修改这个程序,以便用户输入像' X'程序应该关闭输入窗口并退出程序。我不知道如何做到这一点。 我写的代码在下面

#include <iostream>
#include <fstream>
#include <string>

using std::cout;
using std::cin;
using std::endl;

int main()
{
    std::ofstream outputFile;
    outputFile.open("C:\\UseCr\\pp\\qt_projects\\test.txt");
    string sInput;
    cout << "Please Enter the Text ";
    outputFile << sInput << endl;
    std::ifstream outputFile;
    output.close();
    return 0;
}

2 个答案:

答案 0 :(得分:0)

我可能会推荐这样的东西:

#include <iostream>
#include <fstream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main() {
    std::ofstream outputFile(filename); // This will open and close your file. Look up RAII

    string sInput;
    cout << "Please Enter the Text ";
    std::getline(cin, sInput); // Get a string from stdin, strip newline.
    // Check if it's a quit condition
    if(sInput == "x" || sInput == "X") { 
      cout << "Entered 'x', now exiting." << endl;
      qApp->quit(); // or something similar
    }
    // If it's not a quit condition, write to file
    outputFile << sInput << endl;
    // Once outputFile goes out of scope, it is closed.
    return 0;
}

答案 1 :(得分:0)

int main(){

        string sInput;
        std::ofstream outputfile;
        outputFile.open("C:\\UseCr\\pp\\qt_projects\\test.txt");
        cout << "Please enter the text : "<<endl;

        do{
            getline(cin,sInput); //it read from the keyboard what the user write and save into sInput variable
            outputfile << sInput<< endl;
        }while(sInput!= "X" || sInput != "x");
        outputFile.close();
        }
return 0;
}

`