21xrx.com
2025-03-28 22:29:51 Friday
文章检索 我的文章 写文章
如何在C++中将一行文件存储到字符数组中?
2023-07-03 01:35:21 深夜i     15     0
C++ 文件 存储 字符数组 一行

在 C++ 中将一行文件存储到字符数组中可以用以下几种方法:

一、使用 getline 函数

使用 ifstream 类的 getline 函数可以从文件中一行一行地读取数据,并把它存储在一个字符串中。我们可以使用 string 类的成员函数 c_str() 将字符串转换为字符数组,从而把行数据存储到字符数组中。

示例代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
  ifstream myfile("example.txt");
  if (!myfile.is_open())
    cout << "Unable to open file";
    return 1;
  
  string line;
  getline(myfile, line);
  const char* char_line = line.c_str();
  cout << "Line read from file: " << char_line << endl;
  myfile.close();
  return 0;
}

二、使用 fgets 函数

可使用 C 语言的 fgets 函数从文件中读取指定字节数的数据,并把它存储到字符数组中。可使用 C++ 的 istream 类型中的文件指针来打开文件,使用 fgets 函数读取一行数据,并把它存储到字符数组中。

示例代码:

#include <iostream>
#include <cstdio>
using namespace std;
int main() {
  FILE* pFile = fopen("example.txt", "r");
  char mystring[100];
  if (pFile != NULL) {
    if (fgets(mystring, 100, pFile) != NULL)
      cout << "Line read from file: " << mystring;
    
    fclose(pFile);
  } else
    cout << "Unable to open file";
    return 1;
  
  return 0;
}

三、使用 stringstream

可使用 C++ 的 stringstream 类将文件数据存储到字符串流中,并使用 string 类中的成员函数 c_str() 将字符串转换为字符数组。

示例代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
  ifstream myfile("example.txt");
  if (!myfile.is_open())
    cout << "Unable to open file";
    return 1;
  
  stringstream buffer;
  buffer << myfile.rdbuf();
  string file_contents = buffer.str();
  const char* char_line = file_contents.c_str();
  cout << "Contents of file: " << char_line << endl;
  myfile.close();
  return 0;
}

这就是在 C++ 中将一行文件存储到字符数组中的几种方法。使用这些方法可以更方便地在 C++ 中操作文件数据。

  
  

评论区