【发布时间】:2018-11-18 11:06:17
【问题描述】:
我知道这是一个愚蠢的问题!
但我只是不明白如何使用 c++ 一次将我的文件读入数组中
这是我试图做的代码 - 一些尝试的输出。
void readFile()
{
int const maxNumWords = 256;
int const maxNumLetters = 32 + 1;
int countWords = 0;
ifstream fin;
fin.open ("madLib.txt");
if (!fin.is_open()) return;
string word;
while (fin >> word)
{
countWords++;
assert (countWords <= maxNumWords);
}
char listOfWords[countWords][maxNumLetters];
for (int i = 0; i <= countWords; i++)
{
while (fin >> listOfWords[i]) //<<< THIS is what I think I need to change
//buggered If I can figure out from the book what to
{
// THIS is where I want to perform some manipulations -
// BUT running the code never enters here (and I thought it would)
cout << listOfWords[i];
}
}
}
我正在尝试将 madLib.txt 文件中的每个单词(由单词之间的空格定义)放入 listOfWords 数组中,以便我可以逐个字符地执行一些字符串操作。
很明显,我可以从文件中读取并将其放入字符串变量中——但这不是作业(是的,这是针对大学的编码课程)
我已经从一个文件中读取了整数到一个数组中 - 但我不太明白如何在这里应用它......
【问题讨论】:
-
第一个循环读取到文件末尾,第二个循环尝试读取更多内容。在文件末尾不能成功。
-
我刚刚用这个 i
-
@kiltannen 您还必须
clear()输入流。忘记了对不起。但我建议您使用我在回答中勾勒出的方法。