所以我正在研究这个程序,它从文件中获取两个数字作为字符串然后打印它们。我还需要添加前导零,如果有必要,这使我写条件if-else,以便我可以检测是否有任何数字比另一个更大,所以我可以添加前导零。
对于零我使用malloc和动态数组,我也使用strcat将零和实际数字加在一起。它工作正常,但在打印时,它打印零和数字与它们之间的废话。 我如何解决这个问题并删除它们之间的东西? 在下图中,12345644是第一个数字,129是第二个数字。
红色是通缉但蓝色是无意义的,我希望它被删除。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE_MAX 25
int main()
{
FILE *fPTR;
char num_first[SIZE_MAX]; // string input
char num_second[SIZE_MAX];
if ((fPTR = fopen("input.txt", "r")) == NULL) // our file contains two line of integers. one at each
{
puts("File could not be opened.");
}
else
{
if (fgets(num_first, SIZE_MAX, fPTR) != NULL) // reads first line and saves to num_first
puts(num_first); // prints first number
if (fgets(num_second, SIZE_MAX, fPTR) != NULL) // reads second line and saves to num_second
puts(num_second); // prints second number
fclose(fPTR);
}
// getting strings lengths
int fLEN = strlen(num_first) - 1;
int sLEN = strlen(num_second);
int i;
int e = 0; // difference between two string lengths
// here we get the difference and it's the place which i want to shif the arrays
char *temp;
char *zerofill = '\0';
zerofill = (char*)malloc(sizeof(char));
if (fLEN>sLEN) // first string is bigger than second
{
e = fLEN-sLEN;
for(i=0;i<e;i++)
{
int h = 0;
zerofill[i] = '0';
temp = (char*)realloc(zerofill, (i + 2) * sizeof(char));
if (temp != NULL)
{
zerofill = temp; // moving temporary data to main array
}
else
{
free(zerofill);
printf("Error allocating memory!\n");
return 1;
}
}
strcat(zerofill, num_second);
free(zerofill);
}
else if (sLEN>fLEN) // second string is bigger than first
{
e = sLEN-fLEN;
}
else // there is no difference between two strings
{
e = fLEN-sLEN;
}
puts(zerofill);
}