文本文件到数组的传输

Textfile to array transfer

本文关键字:传输 数组 文件 文本      更新时间:2023-10-16

有人能帮我做一个for循环吗?这个循环可以从文本文件中读取并输出到数组中?

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

就我的想法而言,这是错误的。

这就是你可以写的:

// 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。前者将读取一个单词,而后者将读取.

中的一行