简体   繁体   English

用C ++读取文件

[英]file reading in C++

Could someone help me figure out what this C++ code does I got it somewhere but want to understand it. 有人可以帮助我弄清楚我将此C ++代码弄到什么地方,但想了解它的意思。 I have figured out some of it but some things I cannot get my head around. 我已经弄清楚了其中的一些,但是有些事情我无法理解。 Here it is: 这里是:

vector<double> prices;            // vector of option prices
vector<int> strikes;                // vector of strikes
char buffer[100];                   // buffer for line read
char dataBuffer[100];         // stores current data string read
char *str = NULL;                   // pointer to data string
const char *file = "optionData.txt"; // file with option chain info
ifstream fin;                        // input file stream

fin.clear();
fin.open(file);
if (fin.good())
{
    while (!fin.eof()){
        // read in one line at a time
        fin.getline(buffer,sizeof(buffer)/sizeof(buffer[0]));
        ifstream str1(buffer);

        // Get data
        str1 >> dataBuffer; // read data from file
        while (!str1.eof()){
            // read in contract maturity, strike, and price
            str1 >> dataBuffer;       // read option maturity month
            str1 >> dataBuffer;       // read option maturity year

            str1 >> dataBuffer;       / read option maturity strike
            // convert strike char* data to integers
            // and add to strike vector
            strikes.push_back(atoi(dataBuffer));

            str1 >> dataBuffer;       // read option market price
            // convert option price char* data to floats
            // and add to strike vector
            prices.push_back(atof(dataBuffer));
        }

        buffer[strlen(buffer) + 1] = '\0';
    }
}
else
{
    cout << "File not good!" << "\n";
}
// close file
fin.close();

What i dont get is the following 我没有得到的是以下

  1. ifstream str1(buffer);
  2. fin.getline(buffer,sizeof(buffer)/sizeof(buffer[0]));
    particularly sizeof(buffer)/sizeof(buffer[0]) 特别是sizeof(buffer)/sizeof(buffer[0])
  3. buffer[strlen(buffer) + 1] = '\\0';
  4. str1 >> dataBuffer;

The file being read is "optionData.txt" and a sample of it is: 读取的文件是“ optionData.txt”,其示例是:

Jan 03 35.00 40.50 Jan 03 95.00 0.30 
Jan 03 40.00 25.30 Jan 03 100.00 0.20 
Jan 03 45.00 29.50 Jan 03 105.00 0.05 
Jan 03 50.00 16.80 Jan 03 110.00 0.10 
Jan 03 55.00 12.60 Jan 03 115.00 0.15 
Jan 03 60.00 9.30 Jan 03 120.00 0.15 
Jan 03 65.00 6.40 Jan 03 125.00 0.10 
Jan 03 70.00 4.10 Jan 03 130.00 0.10 
Jan 03 75.00 2.60 Jan 03 140.00 0.10 
Jan 03 80.00 1.50 Jan 03 150.00 0.05 
Jan 03 85.00 0.90 Jan 03 155.00 0.00 
Jan 03 90.00 0.50 Jan 03 160.00 0.05

Please be patient with me I am teaching myself c++. 请耐心,我正在自学c ++。 I ran it but it freezes my machine. 我运行了它,但是它冻结了我的机器。

  1. Declares an input stream, opening the file specified in buffer . 声明一个输入流,打开在buffer指定的文件。
  2. It's a standard method to get the number of elements of an array declared on the stack; 这是一种获取堆栈上声明的数组元素数量的标准方法; it takes the whole size of the array (in char s) and divide it by the size of each element; 它占用了整个数组的大小(以char单位),然后将其除以每个元素的大小; in this particular case it is useless since sizeof(char)==1 always, but it can be useful in future it the project is turned to wchar_t s. 在这种特殊情况下,它总是无用的,因为sizeof(char)==1总是如此,但将来在将项目转到wchar_t s时会很有用。
  3. It's not clear to me. 我不清楚。 It seems that the author wanted to NUL -terminate the string, but strlen needs an already terminated string to work, so that thing seems pointless. 看来作者想用NUL终止字符串,但是strlen需要一个已经终止的字符串才能工作,所以这件事似乎毫无意义。
  4. Reads the next field in the specified var, using the correct overload of operator>> . 使用operator>>的正确重载读取指定var中的下一个字段。

Since the questions you're asking are pretty basic, I suggest you to grab a basic C++ book and read it; 由于您所提出的问题是非常基本的,因此建议您阅读一本基本的C ++书籍并阅读; it's quite easy to get bad habits in C++, especially if you learned it "badly" and without always understanding what's going on. 在C ++中养成不良习惯是很容易的,尤其是如果您“不好”学习了C ++并且又不总是了解发生了什么。

By the way, on this line: 顺便说一句,在这一行:

            str1 >> dataBuffer;       / read option maturity strike

there's a slash missing, the compiler will complain. 缺少斜线,编译器会抱怨。

Moreover, iterating on a stream checking just EOF is not a nice thing, you should also check for other stream errors, otherwise you may get caught in an infinite loop (which I think it's what's happening here). 此外,仅检查EOF在流上进行迭代不是一件好事,您还应该检查其他流错误,否则您可能会陷入无限循环(我认为这就是这里发生的事情)。


Edit : uh, now I understand what's going on; 编辑 :嗯,现在我知道发生了什么事; the author of the code wanted to use a stringstream , but instead used an ifstream , which is not good at all for what he wants to do (especially since he tries to open a file named as the whole row just read from file). 该代码的作者希望使用stringstream ,但是使用了ifstream ,这对于他想做的事情根本没有好处(特别是因为他试图打开一个名为从文件中读取的整行的文件)。 By the way, I don't think using a stringstream is useful here, why not just read from the original file? 顺便说一句,我不认为在这里使用stringstream是有用的,为什么不只是从原始文件中读取呢?

It's been a long time since I did C++, but here it goes: 自从我开始使用C ++已经很长时间了,但是在这里:

  1. Declares an I/O stream with the allocated buffer. 声明具有分配的缓冲区的I / O流。
  2. The division takes the size (in bytes) of the whole array and divides it by the size of an element - gives the number of elements. 除法将整个数组的大小(以字节为单位)除以一个元素的大小-得出元素的数量。
  3. Null terminate the string in buffer[]. Null终止buffer []中的字符串。 Add a 0 byte at the end of the character string. 在字符串的末尾添加一个0字节。 This is the C standard string notation. 这是C标准字符串表示法。 However, strlen() expects a null terminated string already in buffer, so I don't quite see what this line contributes. 但是, strlen()期望缓冲区中已经有一个以null结尾的字符串,因此我不太清楚这行的作用。
  4. Reading from the I/O stream and directing the input to the allocated buffer. 从I / O流中读取并将输入定向到分配的缓冲区。 The >> operator is overloaded for the ifstream class. 对于ifstream类,>>运算符已重载。

No wonder your machine got frozen , the inner lop won't stop. 难怪您的机器被冻结了,内部活门不会停止。

anyway, I made a few changes, I didn't want to change the whole code to make it easy for you to understand. 无论如何,我做了一些更改,但我不想更改整个代码以使您更容易理解。

vector<double> prices;            // vector of option prices
vector<int> strikes;                // vector of strikes
string buffer;                   // buffer for line read
string dataBuffer;         // stores current data string read
char *str = NULL;                   // pointer to data string
const char *file = "./optionData.txt"; // file with option chain info
ifstream fin;                        // input file stream

fin.clear();
fin.open(file);
if (fin.good())
{
    while (!fin.eof()){
        // read in one line at a time
  getline(fin,buffer);
        stringstream str1(buffer);
        // Get data
        //str1 >> dataBuffer; // read data from file
        while (str1 >> dataBuffer){
            // read in contract maturity, strike, and price
            // read option maturity month
            str1 >> dataBuffer;       // read option maturity year
            str1 >> dataBuffer;       // read option maturity strike
            // convert strike char* data to integers
            // and add to strike vector
   strikes.push_back(atoi(dataBuffer.c_str()));
            str1 >> dataBuffer;       // read option market price
            // convert option price char* data to floats
            // and add to strike vector
   prices.push_back(atof(dataBuffer.c_str()));
        }
       // buffer[strlen(buffer) + 1] = '\0';
    }
}
else
{
    cout << "File not good!" << "\n";
}
// close file
fin.close();

I changed dataBuffer and buffer into string rather than char[]. 我将dataBuffer和buffer更改为字符串而不是char []。 it's easy to manage. 这很容易管理。

The major change was str1. 主要变化是str1。 I changed it from ifstream into stringstream, since you already have the data in memory. 我将它从ifstream更改为stringstream,因为您已经在内存中存储了数据。

regarding the questions , I think the others answered you very well 关于这些问题,我认为其他人对你的回答很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM