Reputation: 43
My program doesn't export anything to the .txt
file; actually, I can't even compile it in this form.
#include <stdio.h>
typedef struct /*We define structure type to save memory
( im not sure about this!!!) */
{
char name[20];
int num;
} cont;
void input(cont a[],int n) /*With this function i enter data in main program.*/
{
int i;
for(i=0;i<n;i++)
{
printf("Insert name:");
scanf("%s",&a[i].name);
printf("Insert number:");
scanf("%d",&a[i].num);
printf("\n\n\n");
}
}
void export(cont a[],int n) /*Export data that is entered in main program to text file
output.txt that is in same folder as program*/
{
FILE *text;
int i;
text=fopen("output.txt","w");
fprintf(text,"Name:%s\nNumber:%d\n",a[i].name,a[i].num);
fclose(text);
}
void printinprog(cont a[],int n) /*This just prints data in program so we can check
that program works correctly.*/
{
int i;
for(i=0;i<n;i++)
{
printf("Name:%s Number:%d",a[i].name,a[i].num);
printf("\n\n");
}
}
main()
{
cont per[20];
int c;
printf("Enter number of contacts:");
scanf("%d",&c);
input(per,c);
export(per,c);
system("pause");
}
So when i move main part of export function to printinprog function it looks like this:
#include <stdio.h>
typedef struct /*We define structure type to save memory
( im not sure about this!!!) */
{
char name[20];
int num;
} cont;
void input(cont a[],int n) /*With this function i enter data in main program.*/
{
int i;
for(i=0;i<n;i++)
{
printf("Insert name:");
scanf("%s",&a[i].name);
printf("Insert number:");
scanf("%d",&a[i].num);
printf("\n\n\n");
}
}
void printinprog(cont a[],int n) /*This just prints data in program so we can check
that program works correctly.*/
{
int i;
for(i=0;i<n;i++)
{
printf("Name:%s Number:%d",a[i].name,a[i].num);
printf("\n\n");
}
FILE *text;
text=fopen("output.txt","w");
fprintf(text,"Name:%s\nNumber:%d\n",a[i].name,a[i].num);
fclose(text);
}
main()
{
cont per[20];
int c;
printf("Enter number of contacts:");
scanf("%d",&c);
input(per,c);
printinprog(per,c);
system("pause");
}
Now program works but i get wrong data in .txt file and that looks like this.
So i am pretty sure that problem is in typedef struct actually i think there is a problem with data types cuz i define it like cont and that doesnt actually exist so proggram doesnt see that as a text data and the gives wrong data to .txt file.
Upvotes: 0
Views: 3821
Reputation: 1697
Problem is that
FILE *text;
text=fopen("output.txt","w");
fprintf(text,"Name:%s\nNumber:%d\n",a[i].name,a[i].num);
fclose(text);
should be inside the loop, and it's outside it. What's happening is that it uses the last value for i (n) and is essentially printing from random memory locations....
Upvotes: 1