文本文件到数组传输

时间:2014-04-21 14:41:56

标签: c++

有人可以帮我解决一个可以从文本文件中读取并将其输出到数组的for循环吗?

for (int i = 0; i < numCreatures[x]; i++)
    {
        dataFile = creaturesDT[i];
    }

我正在想的是,这是错误的。

1 个答案:

答案 0 :(得分:3)

这是你可以写的:

// Input stream for your file. Passing the file name and it gets open for you
ifstream dataFile("test.txt");

// Array replacement with a proper container
vector<string> stringlist;

// Temporary variable to read the line or word in
string mystring;

// Read continously into the temporary variable until you run out of data
while (getline(dataFile, mystring)) {
    // In each iteration, push the value of the temporary variable
    // to the end of the container
    stringlist.push_back(mystring);
}

// At last, close the file as we do not need it anymore
dataFile.close();

我建议不要使用原始数组,而是使用适当的标准库容器,例如vectorliststring。它还取决于您确切的用例,是否要使用operator>>重载或getline。前者将读一个单词,而后者将读取一行。