page contents

C++ getline():从文件中读取一行字符串

我们知道,getline() 方法定义在 istream 类中,而 fstream 和 ifstream 类继承自 istream 类,因此 fstream 和 ifstream 的类对象可以调用 getline() 成员方法。

我们知道,getline() 方法定义在 istream 类中,而 fstream 和 ifstream 类继承自 istream 类,因此 fstream 和 ifstream 的类对象可以调用 getline() 成员方法。

当文件流对象调用 getline() 方法时,该方法的功能就变成了从指定文件中读取一行字符串。该方法有以下 2 种语法格式:

istream & getline(char* buf, int bufSize);
istream & getline(char* buf, int bufSize, char delim);

其中,第一种语法格式用于从文件输入流缓冲区中读取 bufSize-1 个字符到 buf,或遇到 \n 为止(哪个条件先满足就按哪个执行),该方法会自动在 buf 中读入数据的结尾添加 '\0'。

第二种语法格式和第一种的区别在于,第一个版本是读到 \n 为止,第二个版本是读到 delim 字符为止。\n 或 delim 都不会被读入 buf,但会被从文件输入流缓冲区中取走。

以上 2 种格式中,getline() 方法都会返回一个当前所作用对象的引用。比如,obj.getline() 会返回 obj 的引用。

注意,如果文件输入流中 \n 或 delim 之前的字符个数达到或超过 bufSize,就会导致读取失败。

举个例子:



  1. #include <iostream>

  2. #include <fstream>

  3. using namespace std;

  4. int main()

  5. {

  6. char c[40];

  7. //以二进制模式打开 in.txt 文件

  8. ifstream inFile("in.txt", ios::in | ios::binary);

  9. //判断文件是否正常打开

  10. if (!inFile) {

  11. cout << "error" << endl;

  12. return 0;

  13. }

  14. //从 in.txt 文件中读取一行字符串,最多不超过 39 个

  15. inFile.getline(c, 40);

  16. cout << c ;

  17. inFile.close();

  18. return 0;

  19. }

假设 in.txt 文件中存有如下字符串:

https://six.club/articles/python/newest

则程序执行结果为:

https://six.club/articles/python/newest


当然,我们也可以使用 getline() 方法的第二种语法格式。例如,更改上面程序中第 15 行代码为:



  1. inFile.getline(c,40,'c');

这意味着,一旦遇到字符 'c',getline() 方法就会停止读取。 再次运行程序,其输出结果为:

https://


另外,如果想读取文件中的多行数据,可以这样做:



  1. #include <iostream>

  2. #include <fstream>

  3. using namespace std;

  4. int main()

  5. {

  6. char c[40];

  7. ifstream inFile("in.txt", ios::in | ios::binary);

  8. if (!inFile) {

  9. cout << "error" << endl;

  10. return 0;

  11. }

  12. //连续以行为单位,读取 in.txt 文件中的数据

  13. while (inFile.getline(c, 40)) {

  14. cout << c << endl;

  15. }

  16. inFile.close();

  17. return 0;

  18. }

假设 in.txt 文件中存有如下数据:

https://six.club/articles
https://six.club/articles/python/newest
https://six.club/articles/php/newest

则程序执行结果为:

https://six.club/articles
https://six.club/articles/python/newest
https://six.club/articles/php/newest

attachments-2021-05-Oy3XlXaC60ab90676f624.jpg

  • 发表于 2021-05-24 19:39
  • 阅读 ( 761 )
  • 分类:C/C++开发

0 条评论

请先 登录 后评论
小柒
小柒

1312 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1312 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章