0

Right now, I'm making a quiz where my program reads from a .txt file. I can use getline to read the answers from the .txt using fstream. For example, I have the the string "A. greater B. equal C. less D. invalid"

I've named the string containing this read line answers

I would like it so that each one of my answers A. greater, B. equal, C. less, D. invalid are each put on a separate line. Would the find function work okay here? So far, I haven't had much success.

I should mention that I do get a slight error when using size_t and find. For example, when trying to get question D, I would do this:

size_t posD = question.find("D.");
string strD = question.substr(posD);
string test(strD, question.end());

But, I get an error that says "no instance of constructor matches the argument list" on strD. Is there a fix?

Cheers

Luke Zhang
  • 333
  • 3
  • 13
  • Yes `find` would work fine. Start by finding a part of the string. Then splice it. Then rinse+repeat for all others. – Tas Jan 29 '18 at 22:57
  • *Would the find function work okay here?* I would think yes. *So far, I haven't had much success.* Post what you have tried and indicate where you think you are running into problems. – R Sahu Jan 29 '18 at 23:01
  • YOu are vastly overcomplicating the problem. It is often better to ask how to achieve and effect than to ask how to implement what you have decided is a solution. For example you could include newlines in the string: `string answers = "A. greater\nB. equal\nC. less\nD. invalid";` or use an array of strings: `string answers[] = {"A. greater", "B. equal", "C. less", "D. invalid";`, then print in a loop. – Clifford Jan 29 '18 at 23:18
  • @Clifford Yes, but I am reading from a long .txt file and the format of the answers are in that way – Luke Zhang Jan 29 '18 at 23:23
  • In what world can `getline` be used to _display_ anything, or for that matter `find()` _splice_ anything? The first is an _input_ function, and the second is a `const` function and cannot modify the object. Moreover "_splicing_" is not the operation you are asking about there - to _splice_ means to _join two ends_; here you clearly want to _split_. – Clifford Jan 29 '18 at 23:24
  • @Clifford I am reading from a .txt file using `fstream`. I'll edit that – Luke Zhang Jan 29 '18 at 23:27
  • @LukeZhang : Not in the example in your question you are not; you show an assignment with a literal string const. – Clifford Jan 29 '18 at 23:27
  • @Clifford Okay, edited that once more – Luke Zhang Jan 29 '18 at 23:29
  • Your `no instance of constructor...` issue is a separate question - avoid asking unrelated questions in one post. The "duplicate" question does not answer that question, and now it is closed you'll have to ask again in any event. The object `test` would require a constructor `std::string( size_t, std::string::iterator )` which is not defined, and makes little sense; what do you think `std::string::end()` does? – Clifford Jan 29 '18 at 23:36

0 Answers0