C++读取txt中用逗号、空格、换行分隔的数据
·
更多txt文件处理请见:https://github.com/DandelionLau/txtProcessing
使用C++时,免不了要读取txt文件中的数据,但是不同的数据格式导致读取的方式不同,下面进行一个小结。
1.获取文件夹下的文件名
void getAllFiles(string path, vector<string>& files) {
//文件句柄
long hFile = 0;
//文件信息
struct _finddata_t fileinfo; //很少用的文件信息读取结构
string p; //string类的一个赋值函数:assign(),有很多重载版本
if ((hFile = _findfirst(p.assign(path).append("\\*.txt").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR)) //比较文件类型是否是文件夹
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
files.push_back(p.assign(path).append("/").append(fileinfo.name));
getAllFiles(p.assign(path).append("/").append(fileinfo.name), files);
}
}
else
{
files.push_back(p.assign(fileinfo.name)); //只保存文件名
}
} while (_findnext(hFile, &fileinfo) == 0); //寻找下一个,成功返回0,否则-1
_findclose(hFile);
}
}
2.数据按行排列,如图所示,将其读入数组
void readRowInToArray(fstream &in, string FilePath, int data[ROW]) {
in.open(FilePath, ios::in);//打开一个file
if (!in.is_open()) {
cout << "Can not find target file." << endl;
system("pause");
}
string buff;
int i = 0;
while (getline(in, buff)) {
data[i++] = atof(buff.c_str());
}//end while
in.close();
cout << "get data" << endl;
}
3.数据按列排列,如图所示,将其读入数组
void readColumnInToArray(fstream &in, string FilePath, int data[COLUMN]) {
in.open(FilePath, ios::in);//打开一个file
if (!in.is_open()) {
cout << "Can not find target file." << endl;
system("pause");
}
char buff;
int i = 0;
while (!in.eof()) {
in >> buff;
data[i++] = buff - '0';//获得数字
}//end while
in.close();
cout << "get data" << endl;
}
4.数据为矩阵,如图所示,将其读入矩阵
void readInToMatrix(fstream &in, string FilePath, int data[ROW][COLUMN]) {
in.open(FilePath, ios::in);//打开一个file
if (!in.is_open()) {
cout << "Can not find " << FilePath << endl;
system("pause");
}
string buff;
int i = 0;//行数i
while (getline(in, buff)) {
vector<double> nums;
// string->char *
char *s_input = (char *)buff.c_str();
const char * split = ",";
// 以‘,’为分隔符拆分字符串
char *p = strtok(s_input, split);
double a;
while (p != NULL) {
// char * -> int
a = atof(p);
//cout << a << endl;
nums.push_back(a);
p = strtok(NULL, split);
}//end while
for (int b = 0; b < nums.size(); b++) {
data[i][b] = nums[b];
}//end for
i++;
}//end while
in.close();
cout << "get data" << endl;
}
更多推荐
已为社区贡献4条内容
所有评论(0)