使用fstream读取每个字符包括空格和换行符 [英] using fstream to read every character including spaces and newline

查看:1944
本文介绍了使用fstream读取每个字符包括空格和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 fstream 来读取txt档案。



我使用 inFile>>



我正在编写一个加密程序,所以我需要包括空格和换行符。

解决方案



可能最好的方法是将整个文件的内容读入一个字符串,这可以很容易地使用ifstream的 rdbuf() 方法:

  std :: ifstream in(myfile); 

std :: stringstream buffer;
buffer<< in.rdbuf();

std :: string contents(buffer.str());

现在你可以使用常规的字符串操作, >

Tomek 询问是否要读取文本文件时,同样的方法工作来读取二进制数据,虽然在创建输入文件流时需要提供std :: ios :: binary标志。


I wanted to use fstream to read a txt file.

I am using inFile >> characterToConvert, but the problem is that this omits any spaces and newline.

I am writing an encryption program so I need to include the spaces and newlines.

What would be the proper way to go about accomplishing this?

解决方案

Probably the best way is to read the entire file's contents into a string, which can be done very easily using ifstream's rdbuf() method:

std::ifstream in("myfile");

std::stringstream buffer;
buffer << in.rdbuf();

std::string contents(buffer.str());

You can then use regular string manipulation now that you've got everything from the file.

While Tomek was asking about reading a text file, the same approach will work for reading binary data, though the std::ios::binary flag needs to be provided when creating the input file stream.

这篇关于使用fstream读取每个字符包括空格和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆