【发布时间】:2017-08-31 18:49:01
【问题描述】:
我是 C++ 新手,但我无法完成 lynda.com 讲师提供的这个练习。
我应该创建一个包含多行单词的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; }
【问题讨论】:
-
如果 getline 失败,你仍然会增加 pos。您永远不会在第二个循环中使用计算出的 pos。使用 std::vector 而不是原始数组 - 您可以调用 push_back ,它会随着您阅读文件而增长
-
我相信使用调试器逐行检查代码并检查发生的情况比在 Stack Overflow 上提出这样的问题更好。
-
@NathanOliver,即使我将 while 循环更改为类似于 while (inputfile.good) 的内容,它也只会返回空白空格。这也是我的第三个问题。
-
@Y.Yang 那是一回事。如果您阅读该链接,它将向您展示从文件中读取的正确方法。