21xrx.com
2025-04-08 16:39:55 Tuesday
文章检索 我的文章 写文章
如何使用C++从文件中读取字符串
2023-07-10 21:23:32 深夜i     107     0
C++ 文件操作 读取 字符串 处理

在使用C++编写程序时,有时需要从文件中读取字符串。下面是一些用C++从文件中读取字符串的方法。

1. 使用getline()函数

getline()函数是C++标准库中的一个函数,用于从输入流中读取一行文本,并将其存储在一个字符串中。它的语法如下:

getline(ifstream& in_stream, string& str);

其中,in_stream是输入流对象,str是存储读取到的字符串的变量名。

使用getline()函数从文件中读取字符串的示例代码如下:

#include <iostream>
#include <fstream>
#include <string>
int main()
{
  std::ifstream file("test.txt");
  if (file.is_open()) {
    std::string str;
    while (getline(file, str))
      std::cout << str << std::endl;
    
    file.close();
  }
  else
    std::cout << "Failed to open the file." << std::endl;
  
  return 0;
}

2. 使用get()函数

get()函数可从输入流中读取一个字符。可以通过循环读取字符并将其添加到一个字符串中来读取整个行。使用get()函数从文件中读取字符串的示例代码如下:

#include <iostream>
#include <fstream>
#include <string>
int main()
{
  std::ifstream file("test.txt");
  if (file.is_open()) {
    std::string line;
    char c;
    while (file.get(c)) {
      if (c == '\n') {
        std::cout << line << std::endl;
        line.clear();
      }
      else {
        line += c;
      }
    }
    file.close();
  }
  else
    std::cout << "Failed to open the file." << std::endl;
  
  return 0;
}

以上是两种用C++从文件中读取字符串的方法,适用于不同的场景和需求。请根据具体情况选择使用。同时要注意,使用文件操作时,还需要处理文件不存在等错误情况,以保证程序的正确性和鲁棒性。

  
  

评论区

请求出错了