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 个整数,或者 2 个整数或 1,并且 a、b 和 c 的值只能是可选设置的。

如果输入没有发生转换,则返回零值,在这种情况下,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 回答
0

您的程序在我的系统中运行良好。我Code::Blocks 10.05使用Windows 7.

当您的文件 trianglein.txt 有少于 3 个整数值可供fscanf(). 例如,带有、、trianglein.txt等值的文件会给变量和/或. 因此,在循环的每次迭代执行之前初始化, ,并在阅读后检查它们。11 21 2 3 41 2 3 4 5bca=-1b=-1c=-1

如果您正在运行程序,请检查文件triangleout.txt的访问权限。有时您可能没有对该特定文件的写入权限。

顺便说一句,分类逻辑是错误的。等边三角形不可能是直角三角形。

于 2013-05-20T04:12:19.900 回答
-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 回答