junk output in the array of structs - c

This is my project in the sortstudents() function I try to read from file the data is on one row or one line contentiously when I try to print the array I got junk data
this is example about how data look like in the file (2 records):
1 mohamed talaat €#A
2 ahmed mohamed #A
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
///////////////////////////////////////////////////////////////////////////
struct student
{
char id[5];
char name[30];
int term;
float gpa;
char grade;
};
struct student stu;
typedef struct student stud;
//////////////////////////////////////////////////////////////////////////
//set the cordinate to 0, 0 (top-left corner of window)
//<windows.h> is needed
COORD coord = {0,0};
//////////////////////////////////////////////////////////////////////////
//need cordinate struct to use it
//gotoxy to set coordinate x,y
void gotoxy(int x, int y)
{
//X and Y coordinates
coord.X = x; coord.Y = y;
// ew3a tensa Microsoft
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
//////////////////////////////////////////////////////////////////////////
//print regtangle shape Ascii table www.asciitable.com
// window width = 80 character window hight = 25 character
void drawRectangle()
{
int i, j;
//print the corner rear top left
gotoxy(0,0);
printf("%c",201);
// print 78 line shape = starts from rear top left ended at the top rear right
for(i = 1; i < 78; i++)
{
gotoxy(i, 0);
printf("%c",205);
}
//print the corner rear top right
gotoxy(78,0);
printf("%c",187);
//print the corner rear right side with width = 25
for(i = 1; i < 25; i++)
{
gotoxy(78, i);
//print T-shape at width 6 and after 6 proceed until 25 printing right side
if(i == 6)
{
printf("%c",185);
}
else
{
printf("%c",186);
}
}
//print the corner rear bottom right
gotoxy(78, 25);
printf("%c",188);
// -i- already = 78
// print bottom side pf the regtangle
for(i = 77; i > 0; i--)
{
gotoxy(i,25);
// print T-shape at width 35 and after that proceed until 78 printing rgt base side
if(i == 35)
{
printf("%c",202);
}
else
{
printf("%c",205);
}
}
//print the corner rear bottom left
gotoxy(0,25);
printf("%c",200);
// print T-shape at width 6 and after 6 proceed until 25 printing left side
for(i = 24; i > 0; i--)
{
gotoxy(0,i);
if(i == 6)
{
printf("%c",204);
}
else
{
printf("%c",186);
}
}
// print T-shape at width 36 and connect left side to right side
for(i = 1; i < 78; i++)
{
gotoxy(i,6);
if(i == 35)
{
printf("%c",203);
}
else
{
printf("%c",205);
}
}
// connect middle T-shape at the middle of the regtangle to the base
for(i = 7; i < 25; i++)
{
gotoxy(35,i);
printf("%c",186);
}
}
//////////////////////////////////////////////////////////////////////////
// Build Program window interface using functions --drawRectangle
// with color 1 = Blue & Font color 7 = White
void swindow()
{
int i;
drawRectangle();
gotoxy(28,1);
system("color 17");
printf("STUDENT GRADE SYSTEM");
gotoxy(28,2);
for(i=1;i<21;i++)
{
printf("%c",205);
}
gotoxy(15,3);
printf("College of Computing and Information Technology");
gotoxy(10,4);
printf(" ");
gotoxy(10,5);
printf("Arab Academy for Science, Technology & Maritime Transport");
gotoxy(25,24);
}
//////////////////////////////////////////////////////////////////////////
void print_heading(const char st[])
{
gotoxy(50,8);
printf("%s",st);
}
//////////////////////////////////////////////////////////////////////////
void clearWindow()
{
int i,j;
for(i = 37; i < 78; i++)
{
for(j = 7; j < 25; j++)
{
gotoxy(i,j);
printf(" ");
}
}
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void add()
{
clearWindow();
print_heading("Add Record");
int print = 37;
char ans;
int i;
FILE *fp;
fp = fopen("record.txt","ab+");
if(fp == NULL)
{
MessageBox(0,"Error in Opening file\nMake sure your file is not write protected","Warning",0);
}
else
{
fflush(stdin);
//here i can Add Records ...
////////////////////////////////////////////////////////////////////////////////
gotoxy(print,10);printf("ID: ");gets(stu.id);
gotoxy(print,12);printf("Name: ");gets(stu.name);
gotoxy(print,14);printf("Term: ");scanf("%d",&stu.term);
gotoxy(print,16);printf("Score % : ");scanf("%f",&stu.gpa);
if (stu.gpa>=3.40)
{
stu.grade='A';
}
else {
if (stu.gpa>=2.80)
{stu.grade='B';}
else
{
if (stu.gpa>=2.20)
{stu.grade='C';}
else
{
if (stu.gpa>=2.00)
{stu.grade='D';}
else
{stu.grade='F';}
}
}
}
gotoxy(print,18);printf("GPA: %c",stu.grade);printf("\n");
gotoxy(print,20);printf("Press(Y) to Save (N) for Cancel... ");//scanf("%c",&ans);
ans = getche();
if (ans=='y' || ans=='Y')
{
fwrite(&stu, sizeof(stu), 1, fp);
gotoxy(40,22); printf("The record is sucessfully added");
}
else
{
gotoxy(40,22); printf("Entry process cancelled");
}
}
fclose(fp);
}
//////////////////////////////////////////////////////////////////////////
void search(){
clearWindow();
print_heading("Search Record");
char s_id[5];
int isFound = 0;
gotoxy(37,10);
printf("Enter ID to Search: ");
fflush(stdin);
gets(s_id);
//Read the record file from File
FILE *fp;
fp = fopen("record.txt","ab+");
while(fread(&stu,sizeof(stu),1,fp) == 1)
{
if(strcmp(s_id,stu.id) == 0)
{
isFound = 1;
break;
}
}
if(isFound == 1){
gotoxy(37,12);printf("The record is Found");
gotoxy(37,13);printf("--------------------");
gotoxy(37,14);printf("ID: %s",stu.id);
gotoxy(37,16);printf("Name: %s",stu.name);
gotoxy(37,18);printf("Term: %d",stu.term);
gotoxy(37,20);printf("Score %: %0.1f",stu.gpa);
gotoxy(37,22);printf("GPA: %c",stu.grade);
}else
{
gotoxy(37,12);printf("Sory, No record found in the database");
}
fclose(fp);
}
//////////////////////////////////////////////////////////////////////////
void sortstudents()
{
clearWindow();
FILE *fp;
fp = fopen("record.txt","r");
//////// detect number of characters ////////
char nextChar = getc(fp);
int numCharacters = 0;
while (nextChar != EOF)
{
//Do something else, like collect statistics
numCharacters++;
nextChar = getc(fp);
}
//////// detect number of characters ////////
int chunck = numCharacters/sizeof(stu);
//stud *arr = (stud *)malloc(chunck);
stud starray[25];
int d;
int numStudents = 0;
while( fscanf(fp,"%s%s%d%f%c",stu.id,stu.name,&stu.term,&stu.gpa,&stu.grade) > 0)
{
starray[numStudents++] = stu;
}
gotoxy(37,12);printf("The record is Found");
gotoxy(37,13);printf("--------------------");
gotoxy(37,14);printf("ID: %s",starray[0].id);
gotoxy(37,16);printf("Name: %s",starray[0].name);
gotoxy(37,18);printf("Term: %d",starray[0].term);
gotoxy(37,20);printf("Score %: %0.1f",starray[0].gpa);
gotoxy(37,22);printf("GPA: %c",starray[0].grade);
/*"ID: %s",stu.id);
"Name: %s",stu.name);
"Term: %d",stu.term);
Score %: %0.1f",stu.gpa);
"GPA: %c",stu.grade);*/
fclose(fp);
}
//////////////////////////////////////////////////////////////////////////
void menu(){
int choice;
int x = 2;
while(1)
{
gotoxy(x,10);
printf("1. Add Student");
gotoxy(x,12);
printf("2. Search Student");
gotoxy(x,14);
printf("3. Statistics");
gotoxy(x,16);
printf("4. Close");
gotoxy(x,20);
printf("Please enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:
add();
break;
case 2:
search();
break;
case 3:
sortstudents();
break;
case 4:
exit(0);
break;
default:
break;
}
}
}
//////////////////////////////////////////////////////////////////////////
int main()
{
// draw entry window
//drawRectangle();
swindow();
menu();
//clearWindow();
system("PAUSE");
return 0;
}

In the sortStudents you have a loop in the beginning that will read all characters in the file. Then you attempt to read the files as a kind of records. This usage of fscanf will return EOF as you are attempting to read beyond the end of the file.
And even when you don't read any records into your starray array, you still print values from starray[0] which will be all uninitialized (and therefore contain indeterminate (e.g. seemingly random) values).

Related

Why is NULL printed here? - C-90

The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 500
#define M 100
/*Version 1*/
void replace_word(char *word);
void add_new_word_dictionary(void);
void do_nothing(void);
void return_basic(void);
void check_word(void);
void compute_words(void);
void compute_characters(void);
void compute_ch_sp(void);
void compute_num_dif_words(void);
void create_istogram(void);
void save_file(void);
int get_choice(void);
void return_word(void);
void insert_text(int numwords, char matrix[N][M], int posit);
int main() {
int j;
int choice = 0;
char matrix[N][M];
char word[40] = { "t" };
while (1) {
choice = get_choice();
if (choice == 0) {
insert_text(M, matrix, 1);
}
if (choice == 1) {
add_new_word_dictionary();
}
if (choice == 2) {
do_nothing();
}
if (choice == 3) {
save_file();
}
if (choice == 4) {
compute_words();
}
if (choice == 5) {
break;
}
for (j = 0; j < M; j++) {
printf("%s", matrix[N][M]);
}
}
printf("\n End of Program \n");
return 0;
}
void replace_word(char *word) {
return;
}
void add_new_word_dictionary(void) {
char word[50] = { "s" };
printf("\nPlease enter the word\n");
scanf("\n%s", word);
printf("Your word is %s", word);
return;
}
void do_nothing(void) {
printf("\n do_nothing \n");
return;
}
void return_basic(void) {
printf("\n return basic \n");
return;
}
void check_word(void) {
printf("\n check word \n");
return;
}
void compute_words(void) {
printf("\n compute_words \n");
return;
}
void compute_characters(void) {
printf("\n compute characters \n");
}
void compute_ch_sp(void) {
printf("\n compute_ch_sp \n");
return;
}
void compute_num_dif_words(void) {
printf("\n compute_num_same_words \n");
return;
}
void create_istogram(void) {
printf("\n create istogram \n");
return;
}
void save_file(void) {
printf("\n save_file \n");
return;
}
int get_choice(void) {
int choice = 0;
printf("\n Select a choice from the below \n");
printf("\n Select 0 to add text \n");
printf("\n Select 1 to add new words in the dictionary \n");
printf("\n Select 2 to enter enter correction mode \n");
printf("\n Select 3 to save the text \n");
printf("\n Select 4 to see the statistics about your text \n");
printf("\n Select 5 to exit the program\n");
scanf("\n%d", &choice);
return choice;
}
void insert_text(int numwords, char matrix[N][M], int posit) {
int i;
int j;
char word2[40] = { "" };
while (strcmp(word2, "*T*E*L*O*S*")) {
printf("\n Add the word \n");
scanf("\n%s", word2);
if (posit + 1 > numwords) {
printf("\n Out of Bounds \n ");
}
for (i = numwords - 2; i >= posit; i--) {
strcpy(matrix[i + 1], matrix[i]);
if (!i)
break;
}
strcpy(matrix[posit], word2);
j++;
}
for (i = 0; i < j; i++) {
printf("%s", matrix[i]);
printf("\n j is %d\n", j);
}
return;
}
The problem: I have a function called insert_text. This function adds a string in the 1st position of an array (at least that is what I think it does) and it is called if choice is 0 and executes itself until the string *ΤELOS* is given. When in insert_text I print matrix I get a bunch of *(null)*s... I can count how many words matrix has (by declaring a variable j and incrementing by 1 inside the while loop, but that does not seem to work either. How can I fix this?
The printing code is incorrect: matrix is an array of N arrays of M characters, where you store null terminated C strings. As coded, you pass a single character just beyond the end of the array to printf for %s, which expects a string. The loop should be:
for (j = 0; j < N; j++) {
printf("%s ", matrix[j]);
}
Note that char matrix[N][M]; is uninitialized, so its contents will seem random. Initialize matrix as char matrix[N][M] = { "" };
Also note that in add_new_word_dictionary(), the scanf() conversion should be scanf("%49s", word); to prevent a potential buffer overflow if the user enters a very long word.
Same in insert_text, the code should be scanf("%39s", word2) ans you should test the return value to check for input errors.
Finally, arrays are indexed from 0 in C, so insert_text should be given a position of 0 and the number of words should be N, not M.
Both the test and the insertion loop have problems too.
Here is a modified version:
// call from main as insert_text(N, matrix, 0);
//
void insert_text(int numwords, char matrix[N][M], int posit) {
char word2[40];
int i, j = 0;
for (;;) {
printf("\n Add the word \n");
if (scanf("%39s", word2) != 1) {
break; // end of file or input error
}
if (!strcmp(word2, "TELOS")) {
break; // magic word
}
if (posit >= numwords) {
printf("\n Out of Bounds \n");
break;
}
for (i = numwords - 2; i >= posit; i--) {
strcpy(matrix[i + 1], matrix[i]);
}
strcpy(matrix[posit], word2);
j++;
}
for (i = 0; i < j; i++) {
printf("%s ", matrix[i]);
}
printf("\n j is %d\n", j);
}
Here is a modified version of the whole program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 500
#define M 100
/*Version 1*/
void replace_word(char *word);
void add_new_word_dictionary(void);
void do_nothing(void);
void return_basic(void);
void check_word(void);
void compute_words(void);
void compute_characters(void);
void compute_ch_sp(void);
void compute_num_dif_words(void);
void create_istogram(void);
void save_file(void);
int get_choice(void);
void return_word(void);
void insert_text(int numwords, char matrix[N][M], int posit);
int main() {
int j, done = 0;
char matrix[N][M] = { "" };
while (!done) {
switch (get_choice()) {
case 0:
insert_text(N, matrix, 0);
break;
case 1:
add_new_word_dictionary();
break;
case 2:
do_nothing();
break;
case 3:
save_file();
break;
case 4:
compute_words();
break;
default:
done = 1;
break;
}
for (j = 0; j < N; j++) {
if (matrix[j][0])
printf("%s ", matrix[j]);
}
printf("\n");
}
printf("\n End of Program \n");
return 0;
}
void add_new_word_dictionary(void) {
char word[50];
printf("\nPlease enter the word\n");
if (scanf("%49s", word) == 1)
printf("Your word is %s\n", word);
}
void replace_word(char *word) { printf("\n replace word \n"); }
void do_nothing(void) { printf("\n do_nothing \n"); }
void return_basic(void) { printf("\n return basic \n"); }
void check_word(void) { printf("\n check word \n"); }
void compute_words(void) { printf("\n compute_words \n"); }
void compute_characters(void) { printf("\n compute characters \n"); }
void compute_ch_sp(void) { printf("\n compute_ch_sp \n"); }
void compute_num_dif_words(void) { printf("\n compute_num_same_words \n"); }
void create_istogram(void) { printf("\n create istogram \n"); }
void save_file(void) { printf("\n save_file \n"); }
int get_choice(void) {
int choice = -1;
printf("\nSelect a choice from the below \n");
printf("Select 0 to add text \n");
printf("Select 1 to add new words in the dictionary \n");
printf("Select 2 to enter enter correction mode \n");
printf("Select 3 to save the text \n");
printf("Select 4 to see the statistics about your text \n");
printf("Select 5 to exit the program\n");
scanf("%d", &choice);
return choice;
}
// call from main as insert_text(N, matrix, 0);
//
void insert_text(int numwords, char matrix[N][M], int posit) {
char word2[40];
int i;
for (;;) {
printf("\n Add the word \n");
if (scanf("%39s", word2) != 1) {
break; // end of file or input error
}
if (!strcmp(word2, "TELOS")) {
break; // magic word
}
if (posit >= numwords) {
printf("\n Out of Bounds \n");
break;
}
for (i = numwords - 2; i >= posit; i--) {
strcpy(matrix[i + 1], matrix[i]);
}
strcpy(matrix[posit], word2);
posit++;
}
for (i = 0; i < posit; i++) {
printf("%s ", matrix[i]);
}
printf("\n posit is %d\n", posit);
}

Hanoi Tower Problem using stacks - It is not solving the hanoi problem but moving the disks

//Stack Study by yoonseul at 210719
#include <stdio.h>
#include <stdbool.h>
#define SIZE 9
#define _CRT_SECURE_NO_WARNINGS
typedef struct {
int item[SIZE];
int top;
} Stack;
void InitStack(Stack* pstack)
{
pstack->top = -1;
}
bool IsFull(Stack* pstack)
{
return pstack->top == SIZE - 1;
}
bool IsEmpty(Stack* pstack)
{
return pstack->top == -1
}
int Peek(Stack* pstack)
{
if (IsEmpty(pstack)) {
return -1;
}
return pstack->item[pstack->top];
}
void Push(Stack* pstack, int disk)
{
if (IsFull(pstack)) {
exit(1);
}
pstack->item[++(pstack->top)] = disk;
}
void Pop(Stack* pstack) {
if (IsEmpty(pstack)) {
exit(1);
}
--(pstack->top);
}
int exchange(int x);
int main()
{
int num;
int rod[3][SIZE];
char from='0', to;
int move;
scanf("%d", &num);
InitStack(&rod[0]);
InitStack(&rod[1]);
InitStack(&rod[2]);
for (int i = 0; i < num+1; i++) {
Push(&rod[0], i+1);
Push(&rod[1], 0);
Push(&rod[2], 0);
}
while (from != 'q') {
printf("%3c %3c %3c\n", 'A', 'B', 'C');
for (int i = 0;i<num; i++) {
printf("%3d %3d %3d\n", rod[0][i], rod[1][i], rod[2][i]);
}
scanf("%c %c", &from, &to);
if (from == 'q')
return 0;
int peekF, peekT;
int numF = exchange(from);
int numT = exchange(to);
peekF = Peek(&rod[numF]);
peekT = Peek(&rod[numT]);
if (peekF > peekT && peekT != -1) {
printf("Invalid Move");
}
else {
Pop(&rod[numF]);
Push(&rod[numT],peekF);
}
}
}
int exchange(int x)
{
switch (x) {
case 'A':
return 0;
case 'B':
return 1;
case 'C':
return 2;
}
}
Here is my full code for Hanoi Problem.
The objective is to make a problem that can move this between the rod, and print 'invalid move' if the move is invalid. Also, user can input the number of the disks.
When I debug, there are two errors occur.
One is beneath ' A B C' the last number disk is printed three times. My objective is to print ' 1 0 0'
(ex. if maximum disk is 3,' 3 3 3' is printed.)
edited I solved the first one.
for (int i = 0; i < num + 1; i++) {
Push(&rod[0], i+1);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[1], 0);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[2], 0);
}
I changed disk putting part like like using for statement three times. but I don't know the reason why this happens.
Edited
The hanoi Tower is printed twice, after 2nd scan. I want to know the reason why this happens. It seems like memory problem. I want to know why. I'm new to coding.
PLZ help me. I'm crying.

C enum debugging

I want to change my enum code with related values and want to get same output like before change. But i am getting different output. Codes before change were showed in comment lines. How and why it can be? I give the values to get same output. I can't understand why didn't i get the same output? (Random number not a problem. After change, it is not printing the board, just printing first user value not continue, not getting an error just keeping to look like the ss)
//enum {_,X,O}
enum {X,O,_};
//int user = 1;
//int comp = 2;
int user = 0;
int comp = 1;
void initBoard(int board[]){
int n_pieces_user; //number of pieces for user
int n_pieces_comp; //number of pieces for computer
int n_pieces_sum;
int chosen_player;
int position;
printf("Input number of pieces for user and computer respectively: ");
scanf("%d %d", &n_pieces_user, &n_pieces_comp);
int n_pieces_sum = n_pieces_user + n_pieces_comp;
int arr_pos[n_pieces_sum];
printf("Press 1 to choose Player1, press 2 to Player2 (Player1 plays first!): ");
while(1){
scanf("%d",&chosen_player);
if(chosen_player == 1){ //User plays first
srand((unsigned)time(&t)); //initializes random number generator
for(i=0; i<n_pieces_sum; i++){
position = rand()%SIZE;
for(k=0; k<i; k++){
//while((board[position]==1) || (board[position]==2)){
while((board[position] == 0) || (board[position] == 1)){
position = rand()%SIZE;
arr_pos[i] = position;
}
arr_pos[i] = position;
}
if(i<n_pieces_user){
arr_pos[i] = position;
printf("\nUser's random initial piece position: %d", arr_pos[i]);
board[position] = 0;
}
if(i>=n_pieces_user && i<n_pieces_sum){
arr_pos[i] = position;
printf("\nComputer's random initial piece position: %d", arr_pos[i]);
board[position] = 1;
}
}
turn = comp;
break;
}
else if(chosen_player == 2){ //Computer plays first
srand((unsigned)time(&t)); //initializes random number generator
for(i=0; i<n_pieces_sum; i++){
position = rand()%SIZE;
for(k=0; k<i; k++){
//while((board[position]==1) || (board[position]==2)){
while((board[position]==0) || (board[position]==1)){
position = rand()%SIZE;
arr_pos[i] = position;
}
arr_pos[i] = position;
}
if(i<n_pieces_comp){
arr_pos[i] = position;
printf("\nComputer's random initial piece position: %d", arr_pos[i]);
board[position] = 0;
}
if(i>=n_pieces_comp && i<n_pieces_sum){
arr_pos[i] = position;
printf("\nUser's random initial piece position: %d", arr_pos[i]);
board[position] = 1;
}
}
turn = user;
break;
}else
printf("Choose correct input!\n");
}
printf("\n");
}
void printBoard(const int board[]){
char symbol[] = { 'X','O','_' };
//char symbol[] = { '_','X','O' };
printf("\n BOARD\n\n");
for(i=0; i<SIZE; i++) {
if(i != 0 && i%7 == 0)
printf("\n\n");
printf(" %c ",symbol[board[i]]);
}
printf("\n\n");
}
First output:
Output after change:

Creating a program in C that saves and shows data

I'm new with C, and on the university they are making us create a program that can save data introduced by the user, read the data and check if it’s well introduced. After that it must save that data in each free space, you have 10 empty spaces for saving the data. With all the data saved it must show also the data and compare it with all the data introduced. I made the part of reading the data introduced and cheking if its ok. The problem that I have is that I don’t know how I could make the data base and show that data. Here is the code that I have till now.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[30];
int num_sample;
char section;
int cabin;
int day;
int month;
int year;
}Species;
int menu() {
int op = 0;
printf ("\nPrototype Nature Reserve.\n");
printf ("1. Insert a new species.\n");
printf ("2. List the species housed.\n");
printf ("3. Show stadistics.\n");
printf ("4. Exit.\n");
printf ("\nIntroduce an option: ");
scanf ("%d", &op);
return op;
}
void New_species() {
Species e;
int i, j;
char species[100];
char aux[10];
printf("Enter data:\n");
//A fflush is made to not have a problem with the number entered in the menu
fflush(stdin);
gets (species);
//While it is different from - read the text
for (i = 0; species[i] != '-'; i++) {
e.name[i] = species[i];
}
e.name[i] = '\0';
i++;
//We add 1 to the position i because is ending in - and should start reading from the following
for (j = 0; species[i] != '-'; i++,j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.num_sample = My_atoi(aux);
// Check that the sample is a number and not a character
if (e.num_sample <= 0 || e.num_sample >= 100) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the day introduced
for (j = 0; species[i] != '/'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.day = My_atoi(aux);
//Controls the format of the day
if (e.day <= 0 || e.day > 31) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the month introduced
for (j = 0; species[i] != '/'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.month = My_atoi(aux);
//Controls the format of the month
if (e.month <= 0 || e.month > 12) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the year introduced
for (j = 0; species[i] != '-'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.year = My_atoi(aux);
//Controls the format of the year
if (e.year < 1970 || e.year > 2060) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the section introduced
e.section = species[i];
//Controls that the section is in capital letters
if (e.section < 'A' || e.section > 'Z') {
printf ("--> Error in data format.\n");
}
i+= 2;
//As the cabin is at the end it must reach the \0
for (j = 0; species[i] != '\0'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.cabin = My_atoi(aux);
if (e.cabin < 0 || e.cabin > 20) {
printf ("--> Error in data format.\n");
}
printf ("Species stored successfully (%d/10 free).");
//This printf is just to ensure that the data entered was read correctly
printf ("\n%s", species);
}
int My_atoi(char cad[10]) {
int r = 0;
int i;
for (i = 0; cad[i] != '\0'; i++) {
r = r * 10;
r += cad[i] - '0';
}
return r;
}
void list_species() {
}
void stadistics() {
}
void executeOption(int op) {
switch (op) {
case 1:
New_species();
break;
case 2:
list_species();
break;
case 3:
stadistics();
break;
default:
break;
}
}
int main() {
int op = 0;
do {
op = menu();
executeOption(op);
} while (op != 4);
return 0;
}
I’ve seen that you can use files* so it can create a .txt file for storing but I don’t know how to use it and I don't think that it's allowed in this program.
I'll leave a photo of how it should work
Thanks.
ok u need to save data to a file and load from a file.
here a short code of my and read and write:
#include<stdio.h>
#include<stdlib.h>
typedef struct worker
{
int sal;
char name[25];
}W;
void main()
{
FILE *f;
int i,j=4;
W a[3];
while(j!=3)
{
printf("\nEnter\n[1]write\n[2]read\n[3]exit\n");
scanf("%d",&j);
if(j==1)
{
if (f==NULL)
{
printf("Error!!\n");
exit(0);
}
f=fopen("workers.txt","w");
for(i=0;i<3;i++)
{
printf("\nEnter worker name: ");
scanf("%s",&a[i].name);
printf("\nEnter worker sal: ");
scanf("%d",&a[i].sal);
fprintf(f,"%s %d",a[i].name,a[i].sal);
}
if(j==2)
{
if (f==NULL)
{
printf("Error!!\n");
exit(0);
}
f=fopen("workers.txt","r");
for(i=0;i<3;i++)
{
fscanf(f,"%s %d",a[i].name,&a[i].sal);
printf("\n%s %d",a[i].name,a[i].sal);
}
}
}
fclose(f);}
and I don't think that it's allowed in this program
why wouldn't you be allowed? Yes indeed you can go through two alternatives
To text file
This is the one proposed by dor in his answer where he shows you the way of writing text through fprintf.
To binary file
You can also write to a file using fwrite/fseek like this example I found surfing around you can check it out here -> c-tutorial-binary-file-io
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
my_record.x= counter;
fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile);
}
fclose(ptr_myfile);
return 0;
}
and retrieving back the data from the binary may go this way as the tutorial shows
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
If you are looking for a solution in a .txt file I have a proposal,
#include <stdio.h>
int main(){
FILE *in;
FILE *OUT = fopen("read_at.txt", "w");
char name[20];
char capture[80];
int age = 0;
float grade = 0;
puts("introduce your name:");
scanf("%19s", name);
puts("introduce your age:");
scanf("%i", &age);
puts("introduce your Math grade(0-10):");
scanf("%f", &grade);
fprintf(OUT, "Age %i, Grade %f, Name %s\r\n", age, grade, name);
fclose(OUT);
if(!(in = fopen("read_at.txt","r"))){
fprintf(stderr, "The file could not be opened. \n");
return 1;
}
while (fscanf(in, "Age %i, Grade %f, Name %20[^\n]\n", &age, &grade, name)==3){
printf("A %i years old student has achieved a %f mark in last math exam, that student is: %s", age,grade, name);
}
fclose(in);
}
In this code that I have just created you can see how you can just create one file and read and get its data if it has a concrete format. If you are looking for a database you can just put values separated by “;” and new lines (\n). With that if you save it as .csv you would obtain an excel sheet and quite a good database.
If you are interested in this solution, just let me know if you need any additional help.
Regards,

Weird bug which seems to be solved by adding a surplus line of code. Game of fifteen

This is a puzzle game where in a 4x4 grid one has to arrange 15 numbered tiles in order.
Most of the scenarios, the program runs fine. However, when swapping the "1" digit to the nth row, n-2th column, the program seems to bug and duplicate the number 1.
Here's the catch. When I add a random line of code, say
int blah = 0;
or
printf("abc");
The problem just magically disappears.
Because I'm unable to locate the source of the problem, I'll have to post up the entirety of it.
To see the problem, run the code without any command line arguments, then enter 2 followed by 1.
When I added the random line of code at the end of my main() function, the problem just disappears. Please try it out, and help me find out what's happening; it's really confusing.
#include <stdio.h>
#include <stdlib.h>
int n=4;
int win(int board[n][n]);
void print(int board[n][n]);
int main(int argc, char * argv[])
{
if(argc != 2)
{
printf("No valid number accepted. Board size set as 4x4.\n");
}
else if(argc == 2)
{
n = atoi(argv[1]);
if(n<2 || n>5)
{
printf("No valid number accepted. Board size set as 4x4.\n");
}
else
{
printf("Preparing board of size %dx%d\n",n,n);
}
}
int board[n][n];
printf("\n The aim of the game is to sort the board so that it runs in ascending order, from 1 to %d, from left to right and up to down starting from the top left square. To make a move, enter the number of the tile you want to move. No diagonal movement is allowed.\n\n",n*n-1);
int c = n*n-1;
for(int x = 0;x<n;x++)
{
for(int y=0;y<n;y++)
{
board[x][y] = c;
c--;
}
}
if(n%2==0)
{
int temp1 = board[n-1][n-2];
board[n-1][n-2] = board[n-1][n-3];
board[n-1][n-3] = temp1;
}
print(board);
int spacex = n-1;
int spacey = n-1;
char buffer[10];
while(win(board) == 0)
{
printf("To move, enter the number you wish to move. Take note that this number must be adjacent to the blank space. Diagonal movement is not allowed.\nYour move: ");
fgets(buffer,10,stdin);
int move;
char temp[20];
if(sscanf(buffer," %d %s",&move,temp)!= 1)
{
printf("Enter a number please.\n");
continue;
}
if(move == board[spacex+1][spacey])
{
board[spacex][spacey] = board[spacex+1][spacey];
board[spacex+1][spacey] = 0;
spacex++;
}
else if(move == board[spacex-1][spacey])
{
board[spacex][spacey] = board[spacex-1][spacey];
board[spacex-1][spacey] = 0;
spacex--;
}
else if(move == board[spacex][spacey+1])
{
board[spacex][spacey] = board[spacex][spacey+1];
board[spacex][spacey+1] = 0;
spacey++;
}
else if(move == board[spacex][spacey-1])
{
board[spacex][spacey] = board[spacex][spacey-1];
board[spacex][spacey-1] = 0;
spacey--;
}
else if(move == 0)
{
printf("Enter a valid digit please.\n");
continue;
}
else
{
printf("Enter a valid number please.\n");
continue;
}
printf("\n");
print(board);
}
printf("You won!\n");
}
///////////////////////////////////////////////////////
void print(int board[n][n])
{
for(int x=0;x<n;x++)
{
for(int y=0;y<n;y++)
{
if(board[x][y] == 0)
{
printf("__ ");
}
else
printf("%2d ",board[x][y]);
}
printf("\n\n");
}
}
///////////////////////////////////////////////////////
int win(int board[n][n])
{
int check = 1;
for(int x=0;x<n;x++)
{
for(int y=0;y<n;y++)
{
if(board[x][y] != check)
{
if(x==n-1 && y == n-1);
else
{
return 0;
}
}
check++;
}
}
return 1;
}
Any other comments about the code would be greatly appreciated too. Thanks in advance!
Code is reading out of bounds.
These two variables point to the last elements of the array board:
int spacex = n-1;
int spacey = n-1;
but are used incorrectly in all if statements. whenever a +1 is used, they will read out of bounds or read an incorrect element:
if(move == board[spacex+1][spacey])
{
board[spacex][spacey] = board[spacex+1][spacey];
board[spacex+1][spacey] = 0;
spacex++;
}
else if(move == board[spacex-1][spacey])
{
...
else if(move == board[spacex][spacey+1])
{
board[spacex][spacey] = board[spacex][spacey+1];
...

Resources