我想用来fstream读取txt文件.
我正在使用inFile >> characterToConvert,但问题是这省略了任何空格和换行符.
我正在编写加密程序,所以我需要包含空格和换行符.
什么是实现这一目标的正确方法?
Jas*_*dge 48
可能最好的方法是将整个文件的内容读入一个字符串,这可以使用ifstream的rdbuf()方法非常容易地完成:
std::ifstream in("myfile");
std::stringstream buffer;
buffer << in.rdbuf();
std::string contents(buffer.str());
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用常规字符串操作,因为您已从文件中获取所有内容.
虽然Tomek要求读取文本文件,但是同样的方法将用于读取二进制数据,尽管在创建输入文件流时需要提供std :: ios :: binary标志.
luk*_*uke 22
对于加密,最好以二进制模式打开文件.使用类似的东西将文件的字节放入向量:
std::ifstream ifs("foobar.txt", std::ios::binary);
ifs.seekg(0, std::ios::end);
std::ifstream::pos_type filesize = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::vector<char> bytes(filesize);
ifs.read(&bytes[0], filesize);
Run Code Online (Sandbox Code Playgroud)
编辑:根据评论修复了一个微妙的错误.
Ada*_*erg 14
我没有测试过这个,但我相信你需要清除"skip whitespace"标志:
inFile.unsetf(ios_base::skipws);
Run Code Online (Sandbox Code Playgroud)
我对C++流使用以下参考: IOstream Library
以下 C++ 代码将读取整个文件...
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line;
ifstream myfile ("foo.txt");
if (myfile.is_open()){
while (!myfile.eof()){
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
return 0;
}
发布您的代码,我可以为您的问题提供更具体的帮助...
| 归档时间: |
|
| 查看次数: |
72479 次 |
| 最近记录: |