0

この質問はこれまでに 100 万回も出されていることは知っていますが、ほとんどの質問は必要以上に複雑です。どの行にどのデータが含まれるかはすでにわかっているので、各行を独自の変数としてロードしたいだけです。

たとえば、「settings.txt」では次のようになります。

800
600
32

次に、コードでは、1 行目が int winwidth に設定され、2 行目が int winheight に設定され、3 行目が int wincolor に設定されます。

申し訳ありませんが、私は I/O の初心者です。

4

2 に答える 2

2

おそらくあなたができる最も簡単なことはこれです:

std::ifstream settings("settings.txt");
int winwidth;
int winheight;
int wincolor;

settings >> winwidth;
settings >> winheight;
settings >> wincolor;

ただし、これは各変数が新しい行にあることを保証するものではなく、エラー処理が含まれていません。

于 2012-08-31T02:51:45.857 に答える
0
#include <iostream>
#include <fstream>
#include <string>

using std::cout;
using std::ifstream;
using std::string;

int main()
{
    int winwidth,winheight,wincolor;       // Declare your variables
    winwidth = winheight = wincolor = 0;   // Set them all to 0

    string path = "filename.txt";          // Storing your filename in a string
    ifstream fin;                          // Declaring an input stream object

    fin.open(path);                        // Open the file
    if(fin.is_open())                      // If it opened successfully
    {
        fin >> winwidth >> winheight >> wincolor;  // Read the values and
                           // store them in these variables
        fin.close();                   // Close the file
    }

    cout << winwidth << '\n';
    cout << winheight << '\n';
    cout << wincolor << '\n';


    return 0;
}

ifstream は、cin を使用するのとほぼ同じ方法で、抽出演算子 >> とともに使用できます。明らかに、ファイル I/O にはこれ以外にも多くのことがありますが、要求に応じて、これでシンプルに保たれています。

于 2012-08-31T03:54:51.897 に答える