读书人

请教一个文件操作有关问题

发布时间: 2012-02-29 16:44:11 作者: rapoo

请问一个文件操作问题!
具体是:为了对一个excel表中的数据进行更灵活的操作,我把其转化成txt文本文件。
其中的几行如下:
09:31 6.520 202B
09:31 6.540 507B
09:31 6.520 116S
09:31 6.500 1917S
09:31 6.510 120B
可是采用fread()函数不能够正确的读出.
请问各位大侠,如何操作才能把每一行的数据分别存放在
时间(string),价格(float),手数(int),标志(char)这样的数组中
呢?


[解决办法]
如果你想用把excel里面的数据读出来放到数组里面,那google一下 excel,vc.如果你想读取txt里面的数据到数组里面,那么用fread可以的。首先保证txt里面数据格式正确。然后循环读取。别忘记数据转换。还是不行,那贴代码。
[解决办法]
首先,拆分字符串
//split string by specify delims(work fine)
std::vector <string> split( const string& str, const string& delims, unsigned int maxSplits)
{
std::vector <string> ret;
// Pre-allocate some space for performance
ret.reserve(maxSplits ? maxSplits+1 : 30); // 30 is guessed capacity for most case unsigned int numSplits = 0; // Use STL methods
size_t start, pos,numSplits = 0;
start = 0;
do
{
pos = str.find_first_of(delims, start);
if (pos == start)
{
// Do nothing
start = pos + 1;
}
else if (pos == string::npos || (maxSplits && numSplits == maxSplits))
{
// Copy the rest of the string
ret.push_back( str.substr(start) );
break;
}
else
{
// Copy up to delimiter
ret.push_back( str.substr(start, pos - start) );
start = pos + 1;
}
// parse up to next real data
start = str.find_first_not_of(delims, start);
++numSplits;
} while (pos != string::npos); return ret;
}


[解决办法]


#include "stdio.h "
#include "stdlib.h "

struct _stock
{
char time[10];
float price;
int num;
char flag;

}stock[128];

int main()
{
FILE* file = fopen( "text.txt ", "r ");
int i = 0;

if (!file)
return 1;

while (!feof(file)) {
fscanf(file, "%s\t%f\t%d\t%c\n ", stock[i].time, &stock[i].price, &stock[i].num, &stock[i].flag);
i++;
}

fclose(file);

return 0;
}
[解决办法]
文本文件直接用fgets读出每一行到一个数组,然后去空格或tab,parse出每一列就可以了

读书人网 >C++

热点推荐