I'm new to C++, and I am having trouble doing this exercise given by the lynda.com instructor.
I am supposed to create a txt
file that has lines of words in it. And we read it using ifstream
line by line and store the strings into a string array. (Note: This assignment has other parts which are irrelevant to my question.)
So, I have three questions:
When I am running the solutions given by the instructor, though it compiles and runs, it has the EXC_BAD_ACCESS.
Here is her code:
#include <iostream> #include <cstdlib> #include <ctime> #include <cstring> #include <fstream> using namespace std; string getRandomReply(string [], int); int main() { ifstream inputfile; // Declare an input file inputfile.open("replies.txt", ios::in); char answer[30]; string answers[20]; int pos = 0; // Read from the file until end of file (eof) while (!inputfile.eof()) { inputfile.getline(answer, 30); answers[pos] = answer; pos++; } cout << "Think of a question for the fortune teller, " "\npress enter for the answer " << endl; cin.ignore(); cout << getRandomReply(answers, 20) << endl; return 0; } string getRandomReply(string replies[], int size) { srand(time(0)); int randomNum = rand()%20; return replies[randomNum]; }
Even if this program is functional, I don't understand the need to create char [] and to assign values into the string array through it.
I've written my own version of the code while I was doing the exercise, which compiles and runs but returns with lines of white spaces.
#include <iostream> #include <cstdlib> #include <ctime> #include <cstring> #include <fstream> int main(int argc, const char * argv[]) { std::ifstream inputfile; inputfile.open("replies.txt", std::ios::in); std::string answers[20]; int pos = 0; // Read from the file until end of file (eof) while (inputfile.good()) { getline(inputfile, answers[pos], '\n'); pos++; } for (int i=0; i<20; i++) { std::cout << answers[i] << std::endl; } /* srand(time(0)); std::cout << "Think of a question that you would like to ask fortune teller." << std::endl; int ranNum = rand()%20; std::string answer = answers[ranNum]; std::cout << answer << std::endl; */ return 0; }