0

テキスト ファイルから読み込んで書き込もうとしていますが、コードを実行するたびにテキスト ファイルに何も起こりません。「何も起こらない」とは、プログラムが入力ファイルを読み取らず、出力ファイルにデータがエクスポートされないことを意味します。なぜそれが機能しないのか誰かが指摘できますか?事前に助けてくれてありがとう。これが私のコードです:

#include <stdio.h>
#include <stdlib.h>

FILE *inptr, *outptr; 

int main() {
    int a, b, c;
    inptr = fopen("trianglein.txt","r"); //Initialization of pointer and opening of file trianglein.txt
    outptr = fopen("triangleout.txt","w"); //Initialization of pointer and opening of file triangleout.txt

    while((fscanf(inptr,"%d %d %d",&a, &b, &c))!= EOF){  
        fprintf(outptr,"\n%2d %2d %2d\n",a,b,c); 
        if(a+b>c && b+c>a && c+a>b){
            fprintf(outptr, "This is a triangle.\n"); 
            if(a !=b && b !=c && a!=c){ 
                fprintf(outptr, "This is a scalene triangle.\n");
                if(a==b && a==c && c==b){
                    fprintf(outptr, "This is an equilateral triangle.\n");
                    if(a*a+b*b==c*c || b*b+c*c==a*a || a*a+c*c==b*b){
                        fprintf(outptr, "This is a right trianlge.\n");
                    }
                }
            } 
        }
    }

    return 0;
}

trianglein.txtコンテンツ:

10 12 15
2 3 7
3 4 5
6 9 5
6 6 6
6 8 10
7 7 9
4

4 に答える 4

3

複数の問題。

まず、NULL に対してテストして、inptr と outptr が有効かどうかを確認する必要があります。

次に、fscanf は EOF、0、または > 0 のいずれかを返すことができます。

入力ファイルに有効な入力が含まれていない場合。

また、3 つの int が正常に読み取られたり、2 つの int または 1 が取得され、a、b、c の値がオプションでしか設定されないという問題もあります。

入力で変換が行われなかった場合は、0 の値が返されます。この場合、while ループは終了します。

また、scanf スタイルの関数を使用すると、この入力は成功し、値 1 が返されることに注意してください。

「1ゴミ」

あなたが望むかもしれないのは次のようなものだと思います:

// Somewhere near the top
#include <stderr.h>
// ... other includes

const char* inname = "trianglein.txt";
const char* outname = "triangleout.txt";

// Any other stuff


// Inside main...

// Initialization of pointer and opening of file trianglein.txt
if ((inptr = fopen(inname,"r")) == 0){
  fprintf(stderr, "Error opening file %s: %s", inname, strerror(inname));
  return -1;
}

// Initialization of pointer and opening of file triangleout.txt
if ((outptr = fopen(outname,"w")) == 0){
  fprintf(stderr, "Error opening file %s: %s", outname, strerror(outname));
  return -1;
}


int result;
while(true){
  result = fscanf(inptr,"%d %d %d",&a, &b, &c);
  if (result == EOF)
    break;

  if (result < 3)  // Ignore incomplete lines
    continue;

  // do the normal stuff
}  
于 2013-05-20T04:09:13.003 に答える
-1

入れてみて

fclose(inptr);

fclose(outptr);

コードの最後に。

于 2013-05-20T03:44:08.607 に答える
-2

編集: icktoofay が示唆するように、この答えは間違っています。

ファイルにデータを書き込むには、fclose()またはを実行する必要があります。fflush()これらのコードを直前に挿入しますreturn 0;

fclose(inptr);
fclose(outptr);
于 2013-05-20T03:43:03.153 に答える