本文介绍了从文件中提取第一个和最后一个值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好, 我是一个读取文件并提取值的函数,我该如何仅提取第一个和那个.最后的值.要阅读,我使用此功能:
Hi all, I a function that reads a file and extract the values, how can I extract only the first and the. last values. To read I use this function:
if (csf.Open(fname, CFile::modeRead)) // CStdioFile csf; { while (csf.ReadString(buffer)) //CString buffer; { int out = 0; out = swscanf_s(buffer, _T("%[^,],%[^,],%[^,],%lf"),str1, 2046, str2, 2046, str3, 2046, &db1) ); // my calculations to process the double values here } csf.Close(); }更新的代码:基于KarstenK的代码:-
Updated code: Based on KarstenK''s code :-
if (csf.Open(fname, CFile::modeRead)) // CStdioFile csf; { csf.ReadString(buffer); //here is first read in the buffer int out = 0; out = swscanf_s(buffer, _T("%[^,],%[^,],%[^,],%lf"),str1, 2046, str2, 2046, str3, 2046, &db1) ); pInitialTime = str1; while (csf.ReadString(buffer)) { //AFTER that is the last readin the buffer out = swscanf_s(buffer, _T("%[^,],%[^,],%[^,],%lf"),str1, 2046, str2, 2046, str3, 2046, &db1) ); pFinalTime = str1; } csf.Close(); of.WriteString(FmtValues1(pInitialTime, pFinalTime)); // both pInitialTime and pFinalTime values take the last value }我可以使用它读取每一行并进行处理,但是如何只提取第一个和最后一个值呢?
Using this I can read each line and do processing, but how can I extract only the first and the last values?
推荐答案您只是在Karsten中错过了一个分号'' s代码,while语句末尾的代码.编写这样的while语句也不是一个好习惯.当文件的最后一行为空时,Karsten的代码也没有准备好. 这是一个可以帮助您更好的修订版本: You just missed one semicolon in Karsten''s code, the one at the end of the while statement. It is also no good practice to code a while statement like this. Also Karsten''s code was not prepared for when the last line of the file is empty. Here is a revised version that will help you better: if (csf.Open(fname, CFile::modeRead)) // CStdioFile csf; { csf.ReadString(buffer); //here is first read in the buffer int out = 0; out = swscanf_s(buffer, _T("%[^,],%[^,],%[^,],%lf"),str1, 2046, str2, 2046, str3, 2046, &db1) ); pInitialTime = str1; // allocate a temp buffer CString tempBuffer; // now read all remaining lines of the file without decoding them while (csf.ReadString (tempBuffer)) if (tempBuffer.GetLength() > 0) buffer = tempBuffer; // now the last non-empty line is in the buffer and we decode it out = swscanf_s(buffer, _T("%[^,],%[^,],%[^,],%lf"),str1, 2046, str2, 2046, str3, 2046, &db1) ); pFinalTime = str1; } csf.Close(); of.WriteString(FmtValues1(pInitialTime, pFinalTime)); // both pInitialTime and pFinalTime values take the last value }
if (csf.Open(fname, CFile::modeRead)) // CStdioFile csf; { CString buffer; csf.ReadString(buffer); //here is first read in the buffer while (csf.ReadString(buffer)); //AFTER that is the last readin the buffer
看起来很简单;-)
it looks so easy ;-)
更多推荐
从文件中提取第一个和最后一个值.
发布评论