4

のプログラミング方法を知っていることを期待しています。fstream関数がどのように機能するのかわかりません。

3列のデータを含むデータファイルがあります。データの各行が円、長方形、または三角形のいずれを表すかを対数で判断する必要があります。その部分は簡単です。私が理解していない部分は、関数がどのようにfstream機能するかです。

私は思う:

#include < fstream > 

次に、ファイルオブジェクトを宣言する必要がありますか?

ifstream Holes;

それから私はそれを開きます:

ifstream.open Holes; // ?

適切な構文が何であるかわからず、簡単なチュートリアルを見つけることができません。すべてが私のスキルが処理できるよりもはるかに進んでいるようです。

また、データファイルを読み込んだら、データを配列に配置するための適切な構文は何ですか?

配列T[N]cinその中にfstreamオブジェクトHolesを宣言するだけでいいですか?

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 に答える