21xrx.com
2024-09-20 00:30:14 Friday
登录
文章检索 我的文章 写文章
C++中如何将文件数据存入数组中?
2023-07-05 08:48:59 深夜i     --     --
C++ 文件数据 存入 数组

在C++中,我们可以使用fstream库来读写文件。要把文件数据存入数组中,我们可以遵循以下步骤:

第一步,打开文件

使用fstream库中的ifstream对象来打开文件,例如:


#include <iostream>

#include <fstream>

using namespace std;

int main() {

  ifstream inFile("data.txt"); // 打开文件

  if (!inFile)

    cerr << "Could not open file" << endl;

    return 1;

  

  inFile.close(); // 关闭文件

  return 0;

}

第二步,读取文件数据

在打开文件后,我们可以使用getline()函数读取每一行数据,并把它们存入一个字符串变量中。然后,我们可以使用字符串流stringstream把字符串转换为需要的数据类型,并存入数组中,例如:


#include <iostream>

#include <fstream>

#include <sstream>

using namespace std;

int main() {

  ifstream inFile("data.txt"); // 打开文件

  if (!inFile)

    cerr << "Could not open file" << endl;

    return 1;

  

  int arr[100]; // 定义数组

  string line;

  int i = 0;

  while (getline(inFile, line)) { // 逐行读取文件数据

    stringstream ss(line); // 字符串流

    int data;

    while (ss >> data) { // 把字符串转换成int类型

      arr[i++] = data; // 存入数组

    }

  }

  inFile.close(); // 关闭文件

  // 输出数组

  for (int j = 0; j < i; j++) {

    cout << arr[j] << " ";

  }

  cout << endl;

  return 0;

}

以上代码定义了一个大小为100的int类型数组,并通过getline()函数逐行读取文件数据。然后,使用stringstream把字符串转换成int类型,并存入数组中。

第三步,关闭文件

在文件读写完成后,记得关闭文件,防止资源泄漏,例如:


inFile.close(); // 关闭文件

总结

在C++中,我们可以使用fstream库来读取文件,并使用数组来存储文件数据。我们需要打开文件、读取数据并转换数据类型,并存储到数组中。最后,要记得关闭文件来释放资源。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复