C++ 从文件c+读取数组+;
我正在尝试制作一个程序,到目前为止,它只需要读取一个文件并将其内容保存在一个数组中。cout是一个测试,看看这些单词是否会被保存到数组中,但它不起作用。执行时,它所做的只是打印到屏幕上的空白,最后是文件名C++ 从文件c+读取数组+;,c++,arrays,string,parameters,ifstream,C++,Arrays,String,Parameters,Ifstream,我正在尝试制作一个程序,到目前为止,它只需要读取一个文件并将其内容保存在一个数组中。cout是一个测试,看看这些单词是否会被保存到数组中,但它不起作用。执行时,它所做的只是打印到屏幕上的空白,最后是文件名 #include <string.h> #include <stdlib.h> #include <stdio.h> #include <string> #include <iostream> #include <fstream
#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);
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#定义最大10000
void readFile(fstream和wordFile、字符串单词[]、int和wordarraylelength)
{
字符串字;
int i=0;
而(i 试试这样的方法:
//since you are updating the array pass it in by reference as well.
void readFile(fstream& wordFile, string &words[], int &wordarrayLength)
{
int i=0;
while(i < MAX)
{
//each item in the array has to be it's own string
//the previous code simply reused the same string each time
string word;
getline(wordFile, word);
words[i] = word;
cout << words[i] << endl;
i++;
}
wordarrayLength = i;
wordFile.close();
}
//因为您正在更新数组,所以也通过引用传递它。
void readFile(fstream和wordFile、string和words[],int和wordarraylelength)
{
int i=0;
而(i cout我丢失了编译器正在查找的文件。此代码工作正常。请注意:将每行文本保存到单词[I]
,然后递增I
,然后打印单词[I]的内容
。继续重读上一句话,直到你发现自己的错误。为什么不使用vector@SamVarshavchik将输出到控制台行编辑为难道fstream
的传递方式没有问题。@SamVarshavchik我明白你的意思。代码将字符串存储在字[I]中
但是cout
是数组中尚未定义的下一个字符串…但是如果我更改它cout