Reading numbers from text and order the numbers - c

Complete task:
Write a program that reads from a text file 10 integer numbers. The
file has to be previously created using a different code or by using
the operating system’s facilities. Write the functions that:
- order the integers array in ascending/descending order and displays the result
- count the number of even numbers in the array and display the result
My code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <string>
void cresc(int citire[20]);
FILE *fpointer;
void main()
{
char fisier[12];
int i,citire[20];
printf("Dati un nume fisierului:");
scanf("%s", &fisier);
strcat(fisier, ".txt");
fpointer = fopen(fisier, "w");
fprintf(fpointer, "9865742031");
fclose(fpointer);
fpointer = fopen(fisier, "r");
for (i = 0;i < 9;i++)
fscanf(fpointer, "%d", &citire[i]);
fclose(fpointer);
fpointer = fopen(fisier, "a+");
fprintf(fpointer,"\nNumerele puse in ordine sunt: \n");
cresc(citire);
fclose(fpointer);
_getch();
}
void cresc(int citire[20])
{
int i,temp;
for (i = 0;i < 9; i++)
{
if (citire[i] > citire[i + 1])
{
temp = citire[i];
citire[i] = citire[i + 1];
citire[i + 1] = temp;
}
fprintf(fpointer, "%d", citire[i]);
}
}
Can someone help me?
I manage to solve it, thanks for your help guys.
Here is the problem solved, if someone will need it.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <string>
FILE *fpointer;
void cit(int citire[10]);
int paritate(int citire[10]);
void main()
{
char fisier[12];
int i, citire[10], trecere[10], nrpar;
printf("Dati un nume fisierului:");
scanf("%s", &fisier);
strcat(fisier, ".txt");
fpointer = fopen(fisier, "w");
fprintf(fpointer, "9 8 6 5 7 4 2 0 3 1");
fclose(fpointer);
fpointer = fopen(fisier, "r");
for (i = 0;i < 10;i++)
fscanf(fpointer, "%d", &citire[i]);
fclose(fpointer);
fpointer = fopen(fisier, "a");
fprintf(fpointer, "\nNumerele puse in ordine sunt: \n");
cit(citire);
nrpar = paritate(citire);
fprintf(fpointer, "\n\nSunt %d numere pare", nrpar);
fclose(fpointer);
_getch();
}
void cit(int citire[10])
{
int i,j, temp;
for (i = 0;i < 10; i++)
{
for (j = 0;j<9;j++)
if (citire[j] > citire[j + 1])
{
temp = citire[j];
citire[j] = citire[j + 1]; //9 8 6 5 7 4 2 0 3 1
citire[j + 1] = temp; //buble sort
}
}
for (i = 0;i < 10; i++)
fprintf(fpointer, " %d", citire[i]);
}
int paritate(int citire[10])
{
int i, par=0;
for (i = 0;i < 10; i++)
if (citire[i] % 2 == 0)
par ++;
return par;
}

You wright a string representing a single value to the file, you then read 9 integers from the file but there is a single value. You need to separate the values with a non numerical character, like this
fprintf(fpointer, "9 8 6 5 7 4 2 0 3 1");
and then to read, do this instead
while ((i < 9) && (fscanf(fpointer, "%d", &citire[i]) == 1))
++i;
Fix your cresc() function to make it take the number of elements as a parameter
void cresc(int *citire, int count);
and the for loop
for (i = 0 ; i < count ; ++i)
In your main() call cesc() like this
cresc(citere, i);

Related

How do I write and read files on one program?

I'd like to write two multiplication tables in a txt file on one program, read the written file, and print it out on the screen.
C2374 error occurs in my code.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main(void)
{
//File Write
FILE* fp = fopen("99.txt", "wt");
if (fp == NULL)
{
puts("file open fail.");
return 1;
}
int i = 2;
int j;
for (j = 1; j <= 9; j++)
{
fprintf(fp, "\t %d X %d = %2d \n", i, j, i * j);
}
//File Read
char str[100];
FILE* fp = fopen("99.txt", "rt");
while (fgets(str, sizeof(str), fp) != NULL)
printf(str);
fclose(fp);
return 0;
}
How can I get the 'desired output'?
desired output
I'd really appreciate your help.
You cannot declare FILE *fp twice. Minimized scope of variables. Changed loop condition from j <= 9 to j < 10 which how it's usually done. Use freopen() to change the mode of the file handle:
#include <stdio.h>
int main(void) {
FILE* fp = fopen("99.txt", "wt");
if(!fp) {
puts("file open fail.");
return 1;
}
for (int i = 2, j = 1; j < 10; j++)
fprintf(fp, "\t %d X %d = %2d \n", i, j, i * j);
fp = freopen(NULL, "r", fp);
if(!fp) {
puts("file reopen fail.");
return 1;
}
char str[100];
while (fgets(str, sizeof(str), fp) != NULL)
printf(str);
fclose(fp);
}
and expected output:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18

increment variable doubles at the end of my program

So I have this program where it asks the user for a filename to read, and a filename to save the output to. This program basically counts the frequency of a letter inside the txt file. Here is the program...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char letter[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", FileName[50], SaveFile[50], print[256], stry[50], scount[50], point;
int i, j, count = 0;
FILE * readFile, *saveFile;
printf("Enter a file to read: ");
gets(FileName);
printf("Enter a filename to save results: ");
gets(SaveFile);
printf("Letter Frequency\n\n");
saveFile = fopen(SaveFile, "wb");
for(i = 0; i <= strlen(letter)-1; i++)
{
readFile = fopen(FileName, "r");
while(!feof(readFile))
{
fgets(print, 256, readFile);
for(j = 0; j <= strlen(print); j++)
{
if(toupper(print[j]) == toupper(letter[i]))
{
count++;
}
}
point = letter[i];
stry[0] = point;
sprintf(scount, "%d", count);
if(feof(readFile) && count > 0)
{
printf("%s %d\n", stry, count);
fprintf(saveFile, stry);
fprintf(saveFile, " ");
fprintf(saveFile, scount);
fprintf(saveFile, "\n");
}
}
count = 0;
}
fclose(readFile);
return 0;
}
I input a txt file named readme.txt that I modified. It contains
aaa
bbb
ccc
ddd
But when I run it, and used readme.txt to be read, the output is
A 3
B 3
C 3
D 6
The frequency of letter D must be only 3. I further modified the content of the readme.txt file, and figured out that value of the variable count is doubled when reading the last line. For example, the content of the txt file is
hello mama
hihihi
maria maria
woohoo
the output will be
A 6
E 1
H 6
I 5
L 2
M 4
O 9
R 2
W 2
I read my program so many times already, and I still can't find my wrong doings. I hope you can help me fix this problem. Your help will be very much appreciated!
EDIT:
This is what my code looks like after making the changes that were recommended in the comments section:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char letter[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", FileName[50], SaveFile[50], print[256], stry[50], scount[50], point;
int i, j, count = 0;
FILE * readFile, *saveFile;
printf("Enter a file to read: ");
gets(FileName);
printf("Enter a filename to save results: ");
gets(SaveFile);
printf("Letter Frequency\n\n");
saveFile = fopen(SaveFile, "wb");
for(i = 0; i < strlen(letter); i++){
readFile = fopen(FileName, "r");
while(fgets(print, 256, readFile) != NULL)
{
fgets(print, 256, readFile);
for(j = 0; j <= strlen(print); j++)
{
if(toupper(print[j]) == toupper(letter[i]))
{
count++;
}
}
point = letter[i];
stry[0] = point;
sprintf(scount, "%d", count);
if(feof(readFile) && count > 0)
{
printf("%s %d\n", stry, count);
fprintf(saveFile, stry);
fprintf(saveFile, " ");
fprintf(saveFile, scount);
fprintf(saveFile, "\n");
}
}
count = 0;
}
fclose(readFile);
return 0;
}

Selection sort not working as expected (C language)

I have to sort an array of structs with selection sort, after I read them from a file.txt.
My algorithm is not working as expected, but it always avoid to sort them and it print the struct in decreasing order.
Example of file.txt :
P0 "ANTONIO" 2000 4
P1 "BARTOLOMEO" 1995 6
P2 "CARLO" 2020 1
P3 "DEMETRIO" 1960 2
P4 "ETTORE" 1920 3
P5 "FRANCESCO" 1950 5
Input: 2 5 3 1 6 4
Output: 4 6 1 3 5 2
What am I doing wrong?
Code below:
#include <stdio.h>
#include <stdlib.h>
#define N 7
struct persona
{
char codice[10];
char nome[30];
int anno[10];
int reddito[10];
};
int main()
{
FILE* fp;
fp = fopen("Testo.txt", "r");
struct persona* persona = malloc(sizeof(struct persona) * N);
int i = 0;
int j = 0;
if (fp != NULL)
{
while (i < N-1)
{
fscanf(fp, "%s %s %s %s",
persona[i].codice,
persona[i].nome,
persona[i].anno,
persona[i].reddito);
i++;
}
}
else
{
perror("Errore");
}
fclose(fp);
for(i=0; i<N-2; i++)
{
int min = persona[i].reddito;
for(j=i+1; j<N-1; j++)
{
if(persona[j].reddito < persona[i].reddito)
{
min = persona[j].reddito;
}
persona[N] = persona[j];
persona[j] = persona[i];
persona[i] = persona[N];
}
}
for(i=0; i<N-1;i++)
{
printf("%s\t %s\t %s\t %s\n",
persona[i].codice,
persona[i].nome,
persona[i].anno,
persona[i].reddito);
}
}
You have 6 lines in the file, but you have defined N as 7. It should be updated to 6.
while (i < N-1)
You are reading the first N-2, that is, 5 lines from the file. The 6th line is not being read. Same goes for other loops in the code using N.
int anno[10];
int reddito[10];
You do not need integer array to read the numeric fields in file, an integer should suffice.
As mentioned by #WhozCraig in the comments, the selection sort algorithm is incorrect. Here's the updated code for reference:
#include <stdio.h>
#include <stdlib.h>
#define N 6
typedef struct persona
{
char codice[10];
char nome[30];
int anno;
int reddito;
} PERSONA;
int main()
{
FILE *fp;
if ((fp = fopen("file.txt", "r")) == NULL)
{
perror("\nFile not found");
exit(1);
}
PERSONA *persona = malloc(sizeof(struct persona) * N);
int i = 0, j;
while (i < N)
{ if (fscanf(fp, "%s %s %d %d", persona[i].codice, persona[i].nome, &persona[i].anno, &persona[i].reddito) == EOF) {
break;
}
i++;
}
fclose(fp);
PERSONA temp;
/* selection sort */
for (i = 0; i < N - 1; i++)
{
int jMin = persona[i].reddito;
for (j = i + 1; j < N; j++)
{
if (persona[j].reddito < persona[jMin].reddito)
{
jMin = j;
}
}
if (jMin != i)
{
temp = persona[i];
persona[i] = persona[jMin];
persona[jMin] = temp;
}
}
for (i = 0; i < N; i++)
{
printf("\n%s\t %s\t %d\t %d", persona[i].codice, persona[i].nome, persona[i].anno, persona[i].reddito);
}
}
Further improvements:
You could also calculate the number of lines in the file in the code instead of relying on a hardcoded value N.
The statement to check sets only the min only if this statement is true
if(persona[j].reddito < persona[i].reddito)
try using the qsort function
int cmpfunc (const void * a, const void * b) {
struct persona *p1 = (struct persona *)a;
struct persona *p2 = (struct persona *)b;
if(p1->reddito < p2->reddito) return -1;
if(p1->reddito > p2->reddito) return 1;
return 0;
}
and instead of the for loop, use
qsort(persona, N, sizeof(struct persona), cmpfunc);

Count repeated numbers in a file

So I'm having this file myFile.txt with the following numbers in it: 1 2 3 4 5 6 7 8 9 0 2 3 4 5 6 6 5 4 3 2 1. I'm trying to write a program that calculates how many times a number from 0 to 9 is repeated, so it would be printed out like that Number %d repeats %d times. Right now I'm stuck at printing out the n number of elements of that file, so in example, if I would like to calculate how many times the 15 first numbers repeat themselves, firstly I would print out those 15 numbers, then the number of times each number repeats. But when I'm trying to print out those 15 numbers, it prints me this: 7914880640-10419997104210821064219560-1975428800327666414848.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main() {
FILE *fp;
fp = fopen("myFile.txt", "r");
char c;
int n, i, count = 0;
for (c = getc(fp); c != EOF; c = getc(fp)) {
if (!(c == ' '|| c == '\n'))
count = count + 1;
}
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
int a[n];
if (n <= count) {
for (i = 0; i < n; i++) {
fscanf(fp, "%d", &a[i]);
}
for (i = 0; i < n; i++) {
printf("%d", a[i]);
}
} else {
printf("Error");
}
fclose(fp);
return 0;
}
That's the final solution.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int count_occur(int a[], char exist[], int num_elements, int value)
{
int i, count = 0;
for (i = 0; i<num_elements; i++)
{
if (a[i] == value)
{
if (exist[i] != 0)
return 0;
++count;
}
}
return(count);
}
int main()
{
int a[100],track[10];
FILE *fp;
fp = fopen("myFile.txt", "r");
char c,exist[20]= {0};
int n,i,num,count=0,k=0,eval;
for (c = getc(fp); c != EOF; c=getc(fp))
{
if (!(c==' '|| c=='\n'))
count=count+1;
}
rewind(fp);
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
if (n<=count)
{
while(fscanf(fp, "%d", &num) == 1)
{
a[k] = num;
k++;
}
for (i=0; i<n; i++)
{
printf("%d ", a[i]);
}
}
else
{
printf("Error");
}
fclose(fp);
if (n<=count)
{
for (i = 0; i<n; i++)
{
eval = count_occur(a, exist, n, a[i]);
if (eval)
{
exist[i]=1;
printf("\nNumber %d was found %d times\n", a[i], eval);
}
}
}
return 0;
}

Array issue in C

I have an university project in C programming. I ran into a problem with the following task. My program should order numbers in two arrays. In the first array i must save (the biggest of every fifth element) and that is my problem. I am not sure how to make the loop which reads five elements compare them, take the biggest one, and then continue doing this with the other elements. I am hoping someone to help because I blocked.
#define A 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void show(int x[], int nx); //функция за показване на масивите
float vavedi(int x[], int nx); //функция, чрез която ръчно въвеждаме числата и ги обработваме
FILE* readFile(char* fname); //функция която чете файл и представя съдържанието му като масиви
int main()
{
int call, a = 0, b = 0, mode = 0, i = 0;
int check = 0;
char fail[A];
char* menu[] = {
"PROGRAM STARTED!",
"Enter an option:",
"1 : Write the numbers.",
"2 : Choose from a file.",
"0 : Exit."
};
do {
for (i = 0; i < 5; i++)
printf("%s\n", menu[i]);
check=scanf("%d", &mode);
if (check != 1)
printf("ERROR! Try again!");
switch (mode)
{
case 1: {
//в случай 1 числата се въведждат от потребителя
call = vavedi(a, b);
break;
}
case 2: {
//в случай 2 потребителя използва съществуващ файл
printf("Enter the path of the file you want to open:\n");
scanf("%s", fail);
call = readFile(fail);
if (call == NULL) {
printf("The file doesn't exist! Try again!\n");
}
break;
}
case 0:
break;
default:
{
printf("ERROR! Try again!\n");
}
}
} while (mode != 0);
printf("\nThe program ended!\n");
return 0;
}
void show(int x[], int nx)
{
int k;
for (k = 0; k < nx; k++)
{
printf("\n Element[%d]= %d", k, x[k]);
}
}
float vavedi(int x[], int nx)
{
int call=0;
int enter=0;
int imin, max;
int b[A], c[A];
int i, j, j1, count;
j = 0;
do {
printf("\nCount of the elements:");
scanf("%d", &count);
if (count <= 0 || count > 100)
printf("Invalid input! Try again!\n");
} while (count <= 0 || count > 100);
for (i = 0; i < count; i++)
{
printf("\nEnter an element:");
scanf("%d", &c[i]);
}
printf("\n");
return enter;
}
Update : Including header file mentioned by #pmg.
If i understand correctly, your problem is to find largest element for every five elements:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h> // Put this after your header files
..
.. //Rest of the code.
..
for (i = 0; i < count; i++)
{
printf("\nEnter an element:");
scanf("%d", &c[i]);
}
size_t size = ceil(count/5.0);
memset(b , INT_MIN , size);
for(int i = 0 ; i < count ; i++)
{
b[i/5] = b[i/5] > c[i] ? b[i/5] : c[i];
}
// Print b like this:
for(i = 0 ; i < size; i++)
printf("%d" , b[i] );
Let's see how this works for array of size 9. array's indices will go from 0 to 8 . If I divide each of them by 5, I get 0 for i = 0 to 4 and 1 for i = 5 to 8. Now we can take max over elements in buckets of 5. You seem to be a beginner, hope this helps you in creating better understanding.
The other problem is the following:
{
int c[A], b[A];
int i = 0, j = 0, k = 0, num;
FILE* fp= NULL; //указател за файл
fp = fopen(fname, "r");
if (fp)
{
while (fscanf(fp, "%d", &c[i]) != EOF)
i++;
num=i;
size_t size = ceil(num/5.0);
memset(b , INT_MIN , size);
for(i = 0 ; i < num ; i++)
{
b[i/5] = b[i/5] > c[i] ? b[i/5] : c[i];
}
printf("\nARRAY1:\n");
for(i = 0 ; i < size; i++)
{
buble(b, i);
printf(" Element[%d]=%1d\n", i, b[i]);
}
printf("\nARRAY2:");
buble(c, num);
show(c, num);
printf("\n");
}
fclose(fp);
return fp;
}
It doesn't calculate the rigth way.

Resources