0

すでに存在するファイルに書き込む簡単なプログラムを書こうとしています。このエラーが発生します:

hello2.txt: file not recognized: File truncated
collect2: ld returned 1 exit status

私は何が間違っているのですか?(両方の方法でスラッシュを試しましたが、それでも同じエラーが発生します。)

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
    ofstream outStream;
    outStream.open(hello3.txt);
    outStream<<"testing";
    outStream.close;

    return 0;
}
4

1 に答える 1

5

これには2つのエラーがあります。

  1. hello3.txtは文字列であるため、引用符で囲む必要があります。

  2. std :: ofstream :: close()は関数であるため、括弧が必要です。

修正されたコードは次のようになります。

#include <iostream>
#include <fstream>

int main()
{
    using namespace std; // doing this globally is considered bad practice.
        // in a function (=> locally) it is fine though.

    ofstream outStream;
    outStream.open("hello3.txt");
    // alternative: ofstream outStream("hello3.txt");

    outStream << "testing";
    outStream.close(); // not really necessary, as the file will get
        // closed when outStream goes out of scope and is therefore destructed.

    return 0;
}

そして注意してください:このコードは、以前そのファイルにあったものをすべて上書きします。

于 2011-04-30T01:44:25.617 に答える