我想读取一个文件,这样我就可以使用任何类型的存储(如char array或vector )逐字符访问它(我听说向量更安全、更快)。我的文件大小将在1 MB to 5 MB左右。我已经尝试过向量,但是它读取一个以\n结尾的单词(我的意思是一次读取文件,一次输出一行),而不是单个字符。在row x column wise的上下文中,我的文件大小会有所不同,因此我认为不能使用二维数组。
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
const int MAX_SIZE = 1000;
int main()
{
ifstream hexa;
hexa.open("test.txt");
char* hexarray = new char[MAX_SIZE];
while (!hexa.eof())
{
for (int i = 0; i <= MAX_SIZE; i++)
{
hexa >> hexarray[i];
cout << hexarray[i]<<endl;
}
}
delete[] hexarray;
hexa.close();
return 0;
}使用向量:
vector<string> data;
ifstream ifs;
string s;
ifs.open("test.txt");
while(ifs>>s)
{
data.push_back(s);
}有人能让我知道如何访问我的文件中的一个字符吗?
File content:
-6353
-cf
-CF
0
1
-10
11
111111
-111111
CABDF6
-cabdf6
defc所以我要找array_name[0] = -,array_name[1] = 6,.array_name[n] = c
发布于 2013-12-24 04:00:38
最简单的方法:
#include <iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<iterator>
//...
std::vector<char> v;
std::ifstream hexa("test.txt");
std::copy( std::istream_iterator<char> (hexa),
std::istream_iterator<char>(),
std::back_inserter(v) );
//...
for(std::size_t i=0 ;i < v.size() ;++i)
std::cout << v[i] << " ";https://stackoverflow.com/questions/20754620
复制相似问题