21xrx.com
2024-05-20 13:38:54 Monday
登录
文章检索 我的文章 写文章
C++如何读取文本文件?
2023-07-09 05:00:49 深夜i     --     --
读取 文本文件 C++

C++是一种功能强大的编程语言,可用于许多用途,包括读取文本文件。 C++为读取文本文件提供了许多不同的选项,每种选项都有自己的优点和缺点。以下是一些常用的方法:

1.使用fstream类:

这是读取文本文件的一种常见方法。可以使用fstream类来打开文件并从中读取。以下是打开和读取文件的示例代码:


#include <iostream>

#include <fstream>       // fstream头文件

#include <string>

using namespace std;

int main() {

  ifstream file("test.txt");

  string str;

  if (file.is_open()) {    // 打开文件

    while (getline(file, str)) // 逐行读取并输出

      cout << str << endl;

    

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

  }

  return 0;

}

2.使用getc()函数:

getc()函数是一个从文件中读取字符的函数。可以使用它来逐个字符地读取文本文件中的内容。以下是读取并输出文本文件中字符的示例代码:


#include <iostream>

#include <stdio.h>

#include <stdlib.h>

using namespace std;

int main () {

  FILE *fp;

  int c;

  fp = fopen("test.txt", "r");  // 打开文件

  if (fp) {

   while ((c = getc(fp)) != EOF) // 读取字符

     putchar(c);        // 输出字符

   fclose(fp);          // 关闭文件

  }

  return 0;

}

3.使用fgets()函数:

fgets()函数是一个从文件中读取一行内容的函数。可以使用它来逐行读取文本文件中的内容。以下是读取并输出文本文件中每行的示例代码:


#include <iostream>

#include <stdio.h>

using namespace std;

int main () {

  FILE *fp;

  char str[60];

  fp = fopen("test.txt", "r");  // 打开文件

  if (fp) {

   while (fgets(str, 60, fp)) // 读取每一行

     printf("%s", str);   // 输出每一行

   fclose(fp);        // 关闭文件

  }

  return 0;

}

总体而言,读取文本文件是C++编程中的关键操作之一。C ++提供了许多不同的方法来读取文本文件,每种方法都有自己的优点和缺点。根据需要选择适当的方法来读取文本文件,可以帮助我们更有效地处理数据和实现编程目标。

  
  

评论区

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