fstream的问题

时间:2013-03-26 00:38:26

标签: c++ fstream

我正在向一个ofstream文件写一个向量数组,但某些值没有被写入,I.E。:

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main (){
    char * hold = new char [100];
    vector<double> fx(2049);
    ifstream inputFile;
    ofstream myFile;
    inputFile.open("data.txt");
    myFile.open("test.txt");
    for (int c=0; c<2049; c++){
         inputFile.getline(hold, 100);
         fx[c] = atof(hold);
    }
    for (int c=0; c<2049; c++){
         myFile << fx[c] << "\n";
    }
}

在fx内,后半部分都等于0.(fx [1024]到fx [2048] == 0)。但是,在test.txt中,在应用回车符时,这些0值都不存在。有什么想法吗? 谢谢! (对这些问题的格式化不熟悉......任何使这更容易理解的提示都会受到赞赏。)

注意:我意识到这个程序是多余的。实际程序具有更多功能,这只是一个工作不正确的区域。

2 个答案:

答案 0 :(得分:1)

试试这个

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>

#define MAX_FILE_LINES 2048


using namespace std;

//genarate random double number
double fRand()
{
    double fMin = 100, fMax = 200;
    double f = (double)rand();    
    return fMin + (f / (fMax - fMin));  
}

//init file (if you need to create sample file with list of double numbers, you can use this function)
void fileInit(){    
    ofstream sourceFile;    
    sourceFile.open("D:\\source.txt");
    if (sourceFile.is_open())
    {
        for (int i=0; i<MAX_FILE_LINES; i++){
            sourceFile << fRand() << endl;
        }
    }
}


int main (){
    string buffer;
    vector<double> fx(MAX_FILE_LINES);  
    ifstream sourceFile;
    ofstream destinationFile;
    sourceFile.open("D:\\source.txt");
    destinationFile.open("D:\\destination.txt");

    //reading file lines to vector
    int lineCount =0;
    if (sourceFile.is_open())
      {
        while ( sourceFile.good() )
        {
          getline (sourceFile,buffer);
          fx[lineCount] = atof(buffer.c_str());
          lineCount++;
          if (lineCount == (MAX_FILE_LINES-1)){
              break;
          }
        }
        sourceFile.close();
      }

    //write lines to new file
    if (destinationFile.is_open())
    {
        for (int i=0; i<MAX_FILE_LINES; i++){
         destinationFile << fx[i] << endl;
        }
    }
}

答案 1 :(得分:0)

为什么要使用手动缓冲器拧一次性?你不能节省百万分之一的成本来考虑这里的周期,没有足够的浪费来补偿。

首先考虑消除不必要的陈述和未经检查的失败。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    vector<float> data;
    {
        ifstream ids("source.txt",ios_base::in);
        int linenr = 0;
        for ( string line ; getline(ids,line) ; ) {
            ++linenr;
            decltype(data)::value_type x;
            istringstream s(line);
            if ( s >> x ) 
                data.push_back(x);
            else
                cerr << "crap line "<<linenr<<" ignored: " << line << '\n';
        }
    }
    ofstream ods("object.txt");
    for ( auto x : data )
        ods << x << '\n';
}