How to read a file into an array line by line c++? -
i've written code , file read contains 3 multiple choice questions. program works fine , can store answers there problem. need randomize order of questions every time compile. way read file in arrays. can't seem figure out how that. appreciated. p.s i'm new 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 response number 1\n"; cin >> c; if (c == 'a') cout << "that's wrong\n"; cout << "what's response second question\n"; cin >> d; if (d == 'a'){ cout << "that's correct\n"; } else cout << "that's wrong\n"; return 0; }
you can first put every line std::vector<std::string>
(reference) <vector>
header:
ifstream file_("mpchoice.txt"); vector<string> lines; if (file_.is_open()) { while (getline(file_, line_)) { cout << line_ << '\n'; lines.push_back(line_); } file_.close(); }
and use std::random_shuffle
(reference) <algorithm>
header:
random_shuffle(lines.begin(), lines.end());
here's example demonstrates use of these standard library facilities.
Comments
Post a Comment