简体   繁体   English

为什么在运行以下文件处理 C 程序时输出不符合预期?

[英]Why output is not as expected while running this following File Handling C Program?

This is a code to perform square of a number by taking input from one file and giving output in another file.这是通过从一个文件中获取输入并在另一个文件中提供输出来执行数字平方的代码。

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

void main() {
   FILE *fp1, *fp2;
   char ch;
   fp1 = fopen("new.txt", "w");
   fputs("This is the new file 12",fp1);
   fclose(fp1);
   fp1 = fopen("new.txt", "r");
   fp2 = fopen("new1.txt", "w");

   while ((ch=fgetc(fp1))!=EOF)
   {
         if(isdigit(ch))
         {
            fputc((int)(ch*ch), fp2);
         }

   }

   printf("File copied Successfully!");
   fclose(fp1);
   fclose(fp2);
}

Expected content of new1.txt is 144 new1.txt 的预期内容为 144

Actual content of new1.txt file is aÄ new1.txt 文件的实际内容是 aÄ

the way you do it is wrong.你这样做的方式是错误的。 You aren't multiplying the entire number together.您不是将整个数字相乘。 So you need first to find the entire number in the file.所以你首先需要在文件中找到整个数字。 An easy way is to store all char in an array and keep the length aswell :一个简单的方法是将所有字符存储在一个数组中并保持长度:

 while ((ch=fgetc(fp1))!=EOF)
 {
    if(isdigit(ch))
    {
        storeDigit[gotDigit] = ch;  // keep ref
        gotDigit += 1; // keep length       
    }
 }

Then you can reconstruct the integer with strtol function :然后你可以用 strtol 函数重建整数:

int digit = (int) strtol(storeDigit, NULL, 10);

Now you can calculate the square of this number, and then use the previous array to convert the int result in char array :现在您可以计算这个数字的平方,然后使用前面的数组将 int 结果转换为 char 数组:

digit = digit * digit;
sprintf(storeDigit, "%d", digit);

And to finish, just write the result to the file :最后,只需将结果写入文件:

int i = 0;
while(storeDigit[i] != '\0')
{
    fputc(storeDigit[i], fp2);
    i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM