我是C++的新手,而且我很难执行lynda.com教师给出的这个练习。逐行读取文件并写入C++数组
我应该创建一个txt
文件,其中包含文字。我们使用ifstream
逐行读取并将字符串存储到字符串数组中。 (注:此任务有哪些是无关紧要的,以我的问题的其他部分。)
所以,我有三个问题:
当我运行由导师给出的解决方案,但它可以编译和运行它有EXC_BAD_ACCESS。
这里是她的代码:
#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]; }
即使这个方案是功能性的,我不明白,需要创造的char [],并通过它来分配值到字符串数组。
我在做练习时编写了自己的代码,它编译并运行,但返回空白行。
#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; }
[不要使用while while(!inputfile.eof())'](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – NathanOliver
如果getline失败,仍然会增加pos。你从不在第二个循环中使用计算的pos。而不是原始数组使用std :: vector - 你可以调用push_back,它会随着你读取你的文件而增长 –
我相信逐行调试你的代码,检查发生了什么会更好地为你服务,而不是问这样一个问题在堆栈溢出。 – user0042