21xrx.com
2025-04-01 19:27:17 Tuesday
文章检索 我的文章 写文章
C++ ifstream 和 stringstream 的不同之处
2023-06-29 20:10:51 深夜i     15     0
C++ ifstream stringstream differences comparison

C++中的ifstream和stringstream都是用于处理输入流的类,但它们在一些方面有不同之处。

ifstream是一个input file stream的缩写,它可以用于读取磁盘上的文件。我们可以用它来打开一个文件,并从文件中读取数据。示例如下:

#include<fstream>
#include<iostream>
using namespace std;
int main()
{
  ifstream ifs;
  ifs.open("example.txt");
  if(!ifs.is_open())
  
    cout<<"Error opening file"<<endl;
    return 1;
  
  string str;
  while(getline(ifs, str))
  
    cout<<str<<endl;
  
  ifs.close();
  return 0;
}

上述代码中,我们打开了example.txt文件,并将其内容逐行读入到一个字符串中,并输出到控制台中。

相反,stringstream是一个在内存中创建的字符串流。我们可以使用它来读取、操作和生成在内存中的字符串。这通常用于解析字符串或将数字转换为字符串。示例如下:

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
  string str = "23 45 67";
  stringstream ss(str);
  int n;
  while(ss>>n)
  
    cout<<n<<endl;
  
  return 0;
}

上述代码中,我们将一个字符串“23 45 67”传递给stringstream,然后使用while循环从中读取整数并输出到控制台中。

因此,C++中的ifstream和stringstream是用于处理输入流的类,但它们用于不同的输入源。ifstream用于读取磁盘上的文件,而stringstream用于在内存中读取、操作和生成字符串。

  
  

评论区

请求出错了