21xrx.com
2024-09-19 08:58:19 Thursday
登录
文章检索 我的文章 写文章
C++按行读取文件
2023-07-03 22:28:28 深夜i     --     --
C++ 按行读取 文件

C++是一种非常流行的编程语言,它可以用于开发各种类型的应用程序。在C++中,读取文件是一项常见的操作,可以使用各种不同的方法来完成。本文将介绍如何使用C++按行读取文件。

首先,需要打开要读取的文件。可以使用C++的文件输入流对象来打开文件,例如:


#include <fstream>

using namespace std;

int main()

{

 ifstream inFile;

 inFile.open("input.txt"); //打开input.txt文件

 if (!inFile)

  cout << "无法打开文件";

  return 1;

 

 //读取文件

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

 return 0;

}

在打开文件后,需要使用C++的getline函数逐行读取文件。使用getline函数需要提供两个参数:输入流对象和字符串变量。例如:


string line;

while (getline(inFile, line))

 //处理每行数据

在循环内部,每次调用getline函数会将下一行数据读入到line字符串中。可以在循环内部处理每行数据,例如打印数据:


string line;

while (getline(inFile, line))

 cout << line << endl;

完整的代码如下:


#include <fstream>

#include <iostream>

#include <string>

using namespace std;

int main()

{

 ifstream inFile;

 inFile.open("input.txt"); //打开input.txt文件

 if (!inFile)

  cout << "无法打开文件";

  return 1;

 

 string line;

 while (getline(inFile, line))

  cout << line << endl; //打印每行数据

 

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

 return 0;

}

需要注意的是,在使用getline函数读取文件时,会将换行符也一并读取进来。因此,每行数据中可能包含换行符。如果需要去除换行符,可以使用C++的substr函数和string::npos常量,例如:


string line;

while (getline(inFile, line)) {

 line = line.substr(0, line.find_first_of('\r')); //去除换行符

 cout << line << endl; //打印每行数据

}

在substr函数中,第一个参数表示要截取的子字符串的起始位置,第二个参数表示要截取的子字符串的长度。在使用find_first_of('\r')函数查找到第一个出现'\r'的位置后,就可以用其作为第二个参数去截取子字符串。

在读取文件时,还需要考虑文件编码的问题。如果文件是Unicode编码的,需要进行相应的编码转换。可以使用C++的std::wstring和std::wifstream来读取Unicode编码的文件,例如:


#include <fstream>

#include <iostream>

#include <string>

using namespace std;

int main()

{

 wifstream inFile;

 inFile.open("input.txt", ios::binary); //打开Unicode编码的input.txt文件

 if (!inFile)

  cout << "无法打开文件";

  return 1;

 

 wstring line;

 while (getline(inFile, line))

  wcout << line << endl; //打印每行数据

 

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

 return 0;

}

在使用std::wifstream读取Unicode文件时,需要将打开文件的模式设置为ios::binary。读取到的每一行数据都是std::wstring类型的。在打印数据时,需要使用wcout而不是cout。需要注意的是,使用std::wifstream读取Unicode编码的文件时可能会出现乱码的情况,需要根据具体情况进行解决。

  
  

评论区

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