【发布时间】:2016-11-04 00:49:40
【问题描述】:
我正在尝试制作一个到目前为止只需要读取文件并将其内容保存在数组中的程序。 cout 是一个测试,看看单词是否会保存到数组中,但它没有用。执行时,它所做的只是打印到屏幕空白处,最后打印文件名。
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <ctime>
#include <time.h>
#define MAX 10000
void readFile(fstream& wordFile, string words[], int &wordarrayLength)
{
string word;
int i=0;
while(i < MAX)
{
getline(wordFile,word);
words[i] = word;
i++;
cout << words[i] << endl;
}
wordarrayLength = i;
wordFile.close();
}
int main()
{
string words[MAX];
int arraylength;
fstream file ("words.txt", ios::in);
readFile(file,words,arraylength);
}
【问题讨论】:
-
注意:你把每一行文本保存到
words[i],你递增i,然后打印words[i]的内容。继续重读上一句,直到找出错误为止。 -
为什么不用矢量
-
@SamVarshavchik 将控制台行的输出编辑为
cout << word << endl;,结果是一样的,我认为这是我传递文件参数的方式,但看起来很好。 -
fstream的传递方式没有问题。 -
@SamVarshavchik 我明白你的意思。代码将字符串存储在
words[i]中,但cout是数组中尚未定义的下一个字符串......但是如果我更改它cout << word << endl;输出应该是从文件中提取的数组,它不是,
标签: c++ arrays string parameters ifstream