LoginSignup
70
54

More than 5 years have passed since last update.

C++でテキストに書き出す方法

Posted at

基本的な事柄だが、頻繁に利用するので書き留めておくことに。

手始めに基本となるサンプルコードを。

outputfile01.cpp
#include<iostream>
#include<fstream>

using namespace std;

int main()
{
    ofstream outputfile("test.txt");
    outputfile<<"test";
    outputfile.close();
}

fstreamをincludeして、ofstream 変数名("吐き出したいテキスト名")で定義します。
そして、変数名<<書き出したい内容;で吐き出したい内容を記入。
最後は、変数名.close();と書いて終了させる。

他にもちょっとだけサンプルコードを下に書き残しておきます。

outputfile02.cpp
#include<iostream>
#include<fstream>

#define F "test.txt"

using namespace std;

int main()
{
    char inputTxt;
    ofstream outputfile(F);

    cout<<"何か文字を記入してください。:";
    cin>>inputTxt;
    cout<<"あなたが記入した文字を"<<F<<"に書き出しました。"<<endl;


    outputfile<<inputTxt;
    outputfile.close();
}
outputfile03.cpp
#include<iostream>
#include<fstream>

#define F "test.txt"
#define n 9

using namespace std;

int main()
{
    int i,j,input[n][n];
    ofstream outputfile(F);

    cout<<"\n九九を表示します。\n\n"<<endl;
    outputfile<<"\n九九を表示します。\n\n\n";

    for (int i=1; i<=n; i++) {
        for (int j=1; j<=n; j++) {
            input[i][j]=i*j;
            outputfile<<input[i][j]<<"\t";
            cout<<input[i][j]<<"\t";
        }
        outputfile<<"\n";
        cout<<endl;
    }
    outputfile<<"\n";
    cout<<endl;
    outputfile.close();
}
70
54
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
70
54