4

我的教授非常聪明,但希望像我这样的菜鸟只知道如何编程。我不明白该fstream功能是如何工作的。

我将有一个包含三列数据的数据文件。我将不得不用对数来确定每行数据是否代表一个圆形、矩形或三角形——这部分很容易。我不明白的部分是该fstream功能的工作原理。

我想我:

#include < fstream > 

那么我应该声明我的文件对象吗?

ifstream Holes;

然后我打开它:

ifstream.open Holes; // ?

我不知道正确的语法是什么,也找不到简单的教程。一切似乎都比我的技能更先进。

另外,一旦我读入数据文件,将数据放入数组的正确语法是什么?

我会只声明一个数组,例如并将T[N]对象放入其中吗?cinfstreamHoles

4

2 回答 2

10

基本ifstream用法:

#include <fstream>   // for std::ifstream
#include <iostream>  // for std::cout
#include <string>    // for std::string and std::getline

int main()
{
    std::ifstream infile("thefile.txt");  // construct object and open file
    std::string line;

    if (!infile) { std::cerr << "Error opening file!\n"; return 1; }

    while (std::getline(infile, line))
    {
        std::cout << "The file said, '" << line << "'.\n";
    }
}

让我们更进一步,假设我们想根据某种模式处理每一行。我们为此使用字符串流:

#include <sstream>   // for std::istringstream

// ... as before

    while (std::getline(infile, line))
    {
        std::istringstream iss(line);
        double a, b, c;

        if (!(iss >> a >> b >> c))
        {
            std::cerr << "Invalid line, skipping.\n";
            continue;
        }

        std::cout << "We obtained three values [" << a << ", " << b << ", " << c << "].\n";
    }
于 2011-11-24T17:31:00.887 回答
1

让我逐步介绍阅读文件的每个部分。

#include <fstream> // this imports the library that includes both ifstream (input file stream), and ofstream (output file stream

ifstream Holes; // this sets up a variable named Holes of type ifstream (input file stream)

Holes.open("myFile.txt"); // this opens the file myFile.txt and you can now access the data with the variable Holes

string input;// variable to hold input data

Holes>>input; //You can now use the variable Holes much like you use the variable cin. 

Holes.close();// close the file when you are done

请注意,此示例不处理错误检测。

于 2011-11-24T17:38:21.220 回答