c++ - 文本文件到数组传输

标签 c++

谁能帮我做一个可以从文本文件读取并将其输出到数组的 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。前者读一个字,后者读一行。

关于c++ - 文本文件到数组传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23199630/

相关文章:

c++ - 跟踪 vector 元素地址

c++ - 返回形式参数的引用

c++ - avcodec_decode_video2 : what do the extra bytes prevent?

c++ - 以位计数递增顺序遍历整数的每个位掩码

c++ - Restbed HTTP 客户端空主体

c++ - 动态分配的对象 C++

c++ - 运算符 << 和继承

c++ - 内联函数中 __LINE__ 的行为

c++ - 使用什么 C++ 库来编写跨平台服务/守护进程?

c++ - 如何对多维数组进行排序?