gpt4 book ai didi

c++ - 如何逐字符读取文件并通过 C++ 中的 array_name[index] 访问它

转载 作者:行者123 更新时间:2023-11-30 04:10:12 24 4
gpt4 key购买 nike

<分区>

我想读取一个文件,这样我就可以使用任何类型的存储来逐个字符地访问它,例如 char arrayvector(我听说 vector 更安全并且快点)。我的文件大小将在 1 MB 到 5 MB 左右。我已经尝试过 vector ,但它一次读取一个以 \n 结尾的单词(我的意思是它一次读取文件一次输出一行)而不是单个字符。我的文件在 row x column 上下文中的大小会有所不同,因此我认为不能使用二维数组。

#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 :

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com