其data0.txt的数据是这样的
0,00,000,5,s
0,00,001,6,s
0,00,002,9,s
0,00,003,7,s
0,00,004,5,s
0,00,005,11,s
0,00,006,3,s
0,00,007,3,s
0,00,008,7,s
0,00,009,15,s
0,01,000,1,s
0,01,001,3,s
0,01,002,2,s
0,01,003,7,s
0,01,004,9,s
0,01,005,8,s
0,01,006,6,s
0,01,007,4,s
0,01,008,14,s
//
// main.cpp
// 文件读写
//
// Created by zhoujl on 15/9/11.
// Copyright (c) 2015年 zhoujl. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdio>
struct Data {
int a;
int b;
int c;
int d;
char e;
};
std::vector<Data> data1; //用vector存储文件读出来的数据
//对文件里的整数字符串转化为整型数
int stringToNum(std::string a) {
size_t len = a.length();
int num = 0;
for (size_t i = 0; i < len; i++) {
num = num*10 + a[i] - '0';
}
return num;
}
bool readFromFile() {
const char* rtfFileName = "data0.txt";
std::ifstream fp(rtfFileName);
std::string data_buf;
Data da;
char s = ','; //文件里以逗号为分隔符
int w[5] = {1,2,3,1,1}; //数据的字符个数
if (!fp.is_open()) {
return false;
}
while (fp.peek() !=EOF) {
data_buf.clear();
getline(fp, data_buf);
std::cout << data_buf <<std::endl;
int count = 1;
int pos = 1; //读取字符串位置终点
int startpos = 0; //读取字符串位置起点
std::string rtf_buf;
while (count <= 5) {
std::string stringbuf = data_buf;
rtf_buf = stringbuf.substr(startpos,pos - startpos);
std::cout << rtf_buf <<std::endl;
if (count == 1) {
da.a = stringToNum(rtf_buf);
count++;
} else if (count == 2) {
da.b = stringToNum(rtf_buf);
count++;
} else if (count == 3) {
da.c = stringToNum(rtf_buf);
count++;
} else if (count == 4) {
da.d = stringToNum(rtf_buf);
count++;
} else {
da.e = rtf_buf[0];
count++;
}
startpos = pos+1;
pos = startpos + w[count-1];
//由于第4个数据可能两个字符也有可能1个字符,需对终点重新计算
if (count == 4) {
for (unsigned int i = pos; i < data_buf.length(); i++) {
if (data_buf[i] == s) {
pos = i;
break;
}
}
}
}
data1.push_back(da);
}
return true;
}
int main(int argc, const char * argv[]) {
// insert code here...
if (readFromFile()) {
printf("hh\n");
} else {
printf("55\n");
}
return 0;
}