各种stream

本文详细介绍了C++中使用ifstream和ofstream进行文件读写的方法,包括打开文件的不同模式,如追加、截断等。同时,深入探讨了输入流istream的多种操作,如读取单个字符、字符串,以及如何使用成员函数如getline、get、ignore和read进行高效的数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. ifstream和ofstream

#include<iostream>
#include<fstream>

int main()
{
	//std::ofstream::in  	File open for reading
	//std::ofstream::out	File open for writing
	//std::ofstream::binary Operations are performed in binary mode rather than text
	//std::ofstream::ate	The output position starts at the end of the file.
	//std::ofstream::app	  append
	//std::ofstream::truncate  truncate,Any contents that existed in the file before it is open are discarded.
	
	std::ofstream ofs("test.txt", std::ofstream::out | std::ofstream::app );
	//Returns true if either (or both) the failbit or the badbit error state flags is set for the stream.
	if (ofs.fail())
	{
		std::cout << "ofs: open file failed" << std::endl;
		exit(-1);
	}

	ofs << "song:" << std::endl << "name:" << "my songs know what you did in the dark" << std::endl;
	ofs.close();


	std::ifstream ifs;
	ifs.open("test.txt", std::ifstream::in);
	if (ifs.fail())
	{
		std::cout << "ifs: open file failed" << std::endl;
		exit(-1);
	}
	
	std::string line;
	while (std::getline(ifs, line))
	{
		std::cout << line << std::endl;
		line.clear();
	}

        ifs.close();
	system("pause");

	return 0;
}

2.关于">>"

#include<iostream>
int main()
{
	int input_value;
	//因istream& operator>> (int& val),故下面两句等效
	std::cin >> input_value;
	//std::cin.operator>>(input_value);
	std::cout << input_value << std::endl;

	system("pause");
	return 0;
}
#include<iostream>
int main()
{
	int input_value;
	int value_2;
	//这里能够连续输入时因为“>>”的定义istream& operator>> (int& val); ,返回值仍然为istream,故能够继续输入。
	//下面两句等效
	std::cin >> input_value >> value_2;
	//std::cin.operator>>(input_value).operator>>(value_2);
	std::cout << input_value << std::endl;
	std::cout << value_2 << std::endl;


	system("pause");
	return 0;
}

3.istream成员函数

gcount  Returns the number of characters extracted by the last unformatted input operation performed on the object.

getline  注意: A null character ('\0') is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted.

get Extracts(提取之后std::cin中就不会再存有对应的输入内容) characters from the stream, as unformatted input:

支持的格式有:

(1) single character

(2) c-string

(3) stream buffer

#include<iostream>

int main()
{
	char input[20];
	std::cin.getline(input, 10);
        //std::cin.get(input, 20);
	std::cout << std::cin.gcount() << std::endl;

	system("pause");
	return 0;
}

ignore 对当前获取到的输入内容,抛弃掉遇到制定的字符串之前的内容,保留指定字符串之后的。

#include<iostream>

int main()
{
    char first, last;

    first = std::cin.get();
    std::cin.ignore(32,' ');
    
    last = std::cin.get();
    std::cout << "first:" << first << " last:" << last << std::endl;

    system("pause");
    return 0;
}

 

read  istream& read (char* s, streamsize n);
Extracts n characters from the stream and stores them in the array pointed to by s.

#include<iostream>
#include<fstream>

int main()
{
	std::ifstream ifs("test.txt", std::ifstream::binary);
	if (ifs)
	{
		// change input stream position
		ifs.seekg(0, ifs.end);
		// return input stream position
		int length = ifs.tellg();
		ifs.seekg(0, ifs.beg);

		char* buffer = new char[length+1];
		std::cout << "length: " << length << std::endl;

		ifs.read(buffer, length);
		buffer[length] = '\0';

		std::cout << buffer << std::endl;

		ifs.close();
	}


	system("pause");
	return 0;
}

readsome  streamsize readsome (char* s, streamsize n);

putback

Attempts to decrease the current location in the stream by one character, making the last character extracted from the stream once again available to be extracted by input operations.

#include <iostream>     // std::cin, std::cout
#include <string>       // std::string


int main () {
  std::cout << "Please, enter a number or a word: ";
  char c = std::cin.get();

  std::string str;

  //填充一个c在输入流的“头”,可以保证输入流在用get提取一个字符后仍然保持不变
  std::cin.putback(c);
  getline(std::cin, str);
  std::cout << "You entered a word: " << str << '\n';

  system("pause");

  return 0;
}

 

tellg  streampos tellg(); 

Returns the position of the current character in the input stream. 返回当前位置从开头位置的偏移数。

 

seekg Sets the position of the next character to be extracted from the input stream.

 

### Stream API 使用方法及多种操作详解 #### 创建 StreamStream 可以通过多种方式创建,常见的有从集合、数组或者文件中获取流。以下是一些常用的创建方式: ```java // 从 List 集合创建 Stream List<String> list = Arrays.asList("apple", "banana", "orange"); list.stream(); // 获取 Stream 实例 [^2] // 从数组创建 Stream String[] fruits = {"apple", "banana", "orange"}; Arrays.stream(fruits); // 获取 Stream 实例 [^2] // 从单个值创建 Stream Stream<Integer> stream = Stream.of(1, 2, 3, 4); ``` --- #### 过滤 (filter) `filter` 方法用于筛选满足条件的元素。 ```java List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); numbers.stream() .filter(n -> n % 2 == 0) // 筛选偶数 .forEach(System.out::println); // 输出: 2, 4, 6 ``` --- #### 转换 (map) `map` 方法可以将流中的每个元素映射成另一个形式或结构的新元素。 ```java List<String> words = Arrays.asList("hello", "world"); words.stream() .map(String::toUpperCase) // 将字符串转为大写 .forEach(System.out::println); // 输出: HELLO, WORLD [^3] ``` --- #### 去重 (distinct) `distinct` 方法会移除重复的元素。 ```java List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5); numbers.stream() .distinct() // 移除重复项 .forEach(System.out::println); // 输出: 1, 2, 3, 4, 5 ``` --- #### 排序 (sorted) `sorted` 方法可以根据自然顺序或自定义比较器对流中的元素进行排序。 ```java List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream() .sorted() // 自然顺序排序 .forEach(System.out::println); // 输出: Alice, Bob, Charlie [^2] names.stream() .sorted((a, b) -> b.compareTo(a)) // 降序排序 .forEach(System.out::println); // 输出: Charlie, Bob, Alice ``` --- #### 归约 (reduce) `reduce` 方法可以通过指定的操作符将流中的多个元素逐步归约为单一的结果。 ```java List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.stream() .reduce(0, Integer::sum); // 计算总和 System.out.println(sum); // 输出: 15 ``` --- #### 收集 (collect) `collect` 方法可以把流中的元素收集到其他容器中,比如 `List`, `Set`, 或者 `Map`。 ```java List<String> words = Arrays.asList("hello", "world"); List<String> upperCaseWords = words.stream() .map(String::toUpperCase) .collect(Collectors.toList()); // 收集成列表 System.out.println(upperCaseWords); // 输出: [HELLO, WORLD] ``` --- #### 终端操作 (Terminal Operations) 终端操作触发实际计算过程,并返回最终结果。常见的是 `forEach`, `count`, 和 `findFirst`。 ```java List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); long count = numbers.stream() .filter(n -> n > 3) .count(); // 统计大于 3 的数量 System.out.println(count); // 输出: 2 Optional<Integer> firstEven = numbers.stream() .filter(n -> n % 2 == 0) .findFirst(); // 查找第一个偶数 firstEven.ifPresent(System.out::println); // 输出: 2 ``` --- #### 并行流 (Parallel Streams) 并行流能够利用多核处理器提高性能。 ```java List<Integer> numbers = IntStream.rangeClosed(1, 10_000).boxed().toList(); long parallelSum = numbers.parallelStream() .reduce(0, Integer::sum); // 并行求和 System.out.println(parallelSum); // 输出: 总和 ``` --- #### 结论 Java Stream API 提供了强大的工具来简化集合数据的处理流程[^1]。无论是过滤、转换还是聚合操作,都可以通过简洁而高效的语法实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值