21xrx.com
2024-09-19 09:27:10 Thursday
登录
文章检索 我的文章 写文章
C++文件读取字符串教程
2023-07-04 18:29:50 深夜i     --     --
C++ 文件读取 字符串 教程 文本文件

在C++语言中,文件的读取十分重要,因为很多情况下需要从文件中读取数据进行处理。其中,读取的数据类型不仅仅包括数字和字符,还包括字符串。本篇文章将为大家介绍如何在C++程序中读取文件中的字符串。

1. 打开文件

首先,需要通过以下代码打开要读取的文件:


#include <iostream>

#include <fstream>

using namespace std;

int main()

{

  ifstream file("filename.txt");

  if(!file.is_open())

    cout << "Failed to open the file" << endl;

    return 0;

  

  //在此处写读取字符串的代码

  file.close();

  return 0;

}

这段代码中,我们使用了C++的文件输入流(ifstream),并以只读模式打开文件。如果打开失败,我们输出一个错误信息并结束程序。

2. 读取字符串

接下来,我们将介绍三种不同的方法用于读取文件中的字符串:使用getline()函数、用get()函数获取单个字符和使用read()函数读取多个字符。

2.1 使用getline()函数

getline()函数可以读取整行字符串。在使用之前,需要包含 头文件。下面是使用getline()函数读取文件中每一行的代码:


#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main()

{

  ifstream file("filename.txt");

  if (!file.is_open())

    cout << "Failed to open the file" << endl;

    return 0;

  

  string str;

  while (getline(file, str))

    cout << str << endl; //输出读取到的字符串

  

  file.close();

  return 0;

}

在以上代码中,我们使用了C++的string类,通过getline()函数读取文件中的每一行字符串,并将其输出。

2.2 用get()函数获取单个字符

get()函数可以读取单个字符,我们可以使用循环读取每一个字符。以下是使用get()函数读取文件中每一个字符的代码:


#include <iostream>

#include <fstream>

using namespace std;

int main()

{

  ifstream file("filename.txt");

  if (!file.is_open())

    cout << "Failed to open the file" << endl;

    return 0;

  

  char c;

  while ((c = file.get()) != EOF)

    cout << c; //输出读取到的字符

  

  file.close();

  return 0;

}

在以上代码中,我们使用了一个char类型的变量来存储每一个读取到的字符,并用循环读取整个文件,直到达到文件的结尾。

2.3 使用read()函数读取多个字符

read()函数可以读取多个字符,需要指定读取的字符个数。以下是使用read()函数读取文件中指定字符个数的代码:


#include <iostream>

#include <fstream>

using namespace std;

int main()

{

  ifstream file("filename.txt");

  if (!file.is_open())

    cout << "Failed to open the file" << endl;

    return 0;

  

  char buffer[100];

  file.read(buffer, 100);

  cout << buffer; //输出读取到的字符串

  file.close();

  return 0;

}

在以上代码中,我们定义了一个char类型的数组,用来存储读取到的字符,然后使用read()函数将指定个数的字符读取到数组中。

3. 关闭文件

最后,我们需要使用close()函数关闭文件,释放资源,以便其他程序或进程可以访问该文件。


file.close();

以上就是C++文件读取字符串的教程,希望可以帮助到大家。

  
  

评论区

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