谁能帮我做一个可以从文本文件读取并将其输出到数组的 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();
我建议不要为此使用原始数组,而是使用适当的标准库容器,例如 vector
或 list
和 string
。它还取决于您的具体用例,您是希望使用 operator>>
重载还是 getline。前者读一个字,后者读一行。
关于c++ - 文本文件到数组传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23199630/