【问题标题】:How to read a file into an array line by line c++?c++ - 如何逐行将文件读入数组?
【发布时间】:2016-02-08 02:20:02
【问题描述】:

我已经编写了这段代码,并且我阅读的文件包含 3 个多项选择题。该程序运行良好,我可以存储答案,但有一个问题。每次编译时,我都需要随机化问题的顺序。唯一的方法是读取数组中的文件。我似乎无法弄清楚如何做到这一点。任何帮助表示赞赏。 P.S 我是 C++ 新手

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

using namespace  std;
int main()
{

    char c;
    char d;
    string line_;
    ifstream file_("mpchoice.txt");

    if (file_.is_open())
    {
        while (getline(file_, line_))
        {
            cout << line_ << '\n';
        }
        file_.close();
    }

    cout << "What is your response for number 1\n";
    cin >> c;

    if (c == 'A')
        cout << "That's wrong\n";
    cout << "What's your response for the second question\n";
    cin >> d;

    if (d == 'A'){
        cout << "That's correct\n";
    }
    else
        cout << "That's wrong\n";


    return 0;
}

【问题讨论】:

    标签: c++ arrays file-io


    【解决方案1】:

    您可以先将&lt;vector&gt; 标头中的每一行放入std::vector&lt;std::string&gt; (reference):

    ifstream file_("mpchoice.txt");
    vector<string> lines;
    
    if (file_.is_open())
    {
        while (getline(file_, line_))
        {
            cout << line_ << '\n';
            lines.push_back(line_);
        }
        file_.close();
    }
    

    然后使用&lt;algorithm&gt; 标头中的std::random_shuffle (reference):

    random_shuffle(lines.begin(), lines.end());
    

    这是一个example,它演示了这些标准库工具的使用。

    【讨论】:

      猜你喜欢
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多