将数据保存到txt文件中? C ++

时间:2016-12-24 09:43:09

标签: c++ string c++11

我正在创建一个程序,用户输入mcqs和option然后将数据保存到txt文件中。我怎么能这样做。我试试但它不起作用。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    ofstream outputFile;
    std::string fname;
    cout<<"Enter file name";
    std::getline (std::cin,fname);
    outputFile.open(fname+".txt");
    std::string name;
    std::string mcqs;
    int x;
    cout<<"How many questions want \n";
    cin>>x;

    for(int i=1;i<=x;i=i+1){
        cout<"Enter question "+i;
        std::getline (std::cin,name);
        outputFile << name << endl;
        cout<<"Option A";
        std::getline (std::cin,mcqs);
        outputFile << mcqs << endl;
        cout<<"Option B";
        std::getline (std::cin,mcqs);
        outputFile << mcqs << endl;
        cout<<"Option C";
        std::getline (std::cin,mcqs);
        outputFile << mcqs << endl;
        cout<<"Option D";
        std::getline (std::cin,mcqs);
        outputFile << mcqs << endl;
    }

    outputFile.close();
    cout << "Done!\n";
    getchar();
    return 0;
}

我想在mcqs file.Thanks

中保存txt和选项

2 个答案:

答案 0 :(得分:0)

你的问题是用cin来获取问题编号。您可以使用get_line和stringstream来读取数字。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
    ofstream outputFile;
    std::string fname;
    std::string str;
    stringstream ss;
    int x;

    cout<<"Enter file name:";
    std::getline (std::cin,fname);
    outputFile.open(fname+".txt");

    cout<<"How many questions want \n";
    std::getline (std::cin,str);
    ss << str;
    ss >> x;
    if (x == 0)
        cout << "Invalid question number...!" << endl;

    for(int i=1;i<=x;i=i+1){
            cout<<"Enter question " << i << ":";
            std::getline (std::cin,str);
            outputFile << str << endl;

            cout<<"Option A:";
            std::getline (std::cin,str);
            outputFile << str << endl;

            cout<<"Option B:";
            std::getline (std::cin,str);
            outputFile << str << endl;

            cout<<"Option C:";
            std::getline (std::cin,str);
            outputFile << str << endl;

            cout<<"Option D:";
            std::getline (std::cin,str);
            outputFile << str << endl;
    }

    outputFile.close();
    cout << "Done!\n";
    getchar();
    return 0;
}

答案 1 :(得分:0)

确保包含在顶部,而ofstream是名称空间std。

的成员