C++ 逐行读取文件并写入C++;
我应该创建一个C++ 逐行读取文件并写入C++;,c++,arrays,ifstream,C++,Arrays,Ifstream,我应该创建一个txt文件,其中有几行字。我们使用ifstream逐行读取它,并将字符串存储到字符串数组中。(注意:本作业还有其他与我的问题无关的部分。) 因此,我有三个问题: 当我运行讲师给出的解决方案时,虽然它编译并运行,但它具有EXC\u BAD\u访问权限 这是她的密码: #include <iostream> #include <cstdlib> #include <ctime> #include <cstring> #include &l
txt
文件,其中有几行字。我们使用ifstream
逐行读取它,并将字符串存储到字符串数组中。(注意:本作业还有其他与我的问题无关的部分。)
因此,我有三个问题:
#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];
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
字符串getRandomReply(字符串[],int);
int main()
{
ifstream输入文件;
//声明输入文件
打开(“repress.txt”,ios::in);
答案[30];
字符串答案[20];
int pos=0;
//从文件读取,直到文件结束(eof)
而(!inputfile.eof())
{
getline(答案,30);
答案[位置]=答案;
pos++;
}
哎呀,我想我不会继续这门课了
在您的教师代码中,我猜测(但不能确定,因为您尚未提供输入)您的答案索引数组(pos
)正在从数组末尾运行,并在教师代码中为您提供了EXEC\u BAD\u访问权限
如果函数未提取字符,或者
一旦有(n-1)个字符,就找不到定界字符
已经写给s。请注意,如果后面的字符
输入序列中的这些(n-1)字符正是
在分隔字符时,也会提取该字符,并且不会显示failbit标志
set(提取的序列长度正好为n个字符)
如果任何问题长度超过30个字符,则此表单中的inputfile.getline(answer,30)将在ifstream上设置failbit,因为它尚未到达分隔符(默认为换行符)
在不更改任何数据结构的情况下(在C++中有更好的数据结构),如果您添加以下内容,它可能会起作用:
// Read from the file until end of file (eof)
while (!inputfile.eof())
{
inputfile.getline(answer, 30);
answers[pos++] = answer;
while (!inputfile)
{
inputfile.clear();
inputfile.getline(answer, 30);
}
}
这将在每次调用getline后清除failbit,并在超过30个字符时尝试完成读取该行。问题是,如果设置了failbit,循环将永远运行,因为!ifstream.eof()而条件从未满足。这意味着您的pos
索引将永远递增,并从数组的末尾运行
文件中的问题可能比固定大小的数组答案所能存储的问题还多
使用调试器的注释并不好笑。这是解决这些问题的方法。您需要一些关于Xcode调试器的初学者阅读材料(可能?)。对于几乎任何初学者操作(检查变量值、设置断点等)这一切都可以通过GUI完成,应该非常简单
关于您的代码(最好不要在StackOverflow上混淆两个问题),在添加了包含std::string和getline重载的include
之后,它对我来说运行得很好。但是,我没有与您相同的输入。在调用getline的循环中设置一个断点。如果路径错误或读取输入时出现问题,您甚至不会进入该循环,并且您将迭代一组空字符串并将其打印出来。如果getline失败,您仍然会增加pos。您永远不会在第二个循环中使用计算出的pos。使用std::vector代替原始数组-您可以调用push_back,它会随着您读取文件而增长。我相信,使用调试器逐行检查代码并检查g继续比在堆栈溢出时问这样的问题更好。@NathanOliver,即使我确实将while循环更改为类似while(inputfile.good)的内容,它也会返回空白。这也是我的第三个问题。@Y.Yang这也是同样的问题。如果你阅读了链接,它会告诉你从文件读取的正确方法。
// Read from the file until end of file (eof)
while (!inputfile.eof())
{
inputfile.getline(answer, 30);
answers[pos++] = answer;
while (!inputfile)
{
inputfile.clear();
inputfile.getline(answer, 30);
}
}