Hello good people of Stack Overflow. Need some help with my code. I am basically trying to put the data that is stored in the variables itemCode, itemName, pricepu, and stock into array and I have NO IDEA how to do so..
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#define totalitems 20
#define maxitems 300
void mainmenu(void);
void alt_menu(void);
void purchase(void);
void edit_item(void);
void update_item(void);
void del_item(void);
void shw_item(void);
void invent_menu(void);
void alt_invent_menu(void);
void daily_trans(void);
void exit_escape(void);
void back_inventmenu(void);
void back_menu(void);
void gst_array(void);
char invent_back, back; //global declarations
char input, newinput;
char *barcode;
char taxitems[20][20];
char ntaxitems[20][20];
char line[2048];
char *itemCode[20][20];
char itemName[20][20];
unsigned char pricepu[10][20];
char stock[10][20];
int i, ret, quantpurchase;
double total;
void purchase() {
char exitcode[] = "-1";
barcode = (char*) malloc(5);
printf(" Please key in the barcode number of the product: ");
scanf(" %s", barcode);
while(strcmp(exitcode, barcode) != '\0') {
double priceint;
FILE *gst = fopen("gst.txt", "r");
FILE *ngst = fopen("ngst.txt", "r");
printf("\n");
printf("\n Item Code Entered: %s\n", barcode);
while(fgets(line, sizeof(line), gst) != NULL) { //while fgets does not fail to scan a line
if(sscanf(line, "%[^;];%[^;];%[^;];%[^;]", itemCode, itemName, pricepu, stock) != 4) {
//If sscanf failed to scan everything from the scanned line
//%[^;] scans everything until a ';'
printf("Bad line detected\n");
exit(-1); //Exit the program
}
for (i=0; i < totalitems; i++) {
if (strcmp(itemCode[i], barcode) == '\0') {
printf("\n");
printf(" Item Found.\n");
printf("\n");
printf("===========================================================================\n");
printf(" Item code\t Item name \t\t\tPrice\t Stock Available \n");
printf("===========================================================================\n");
printf(" %-10s\t %-16s\t\t%s\t %s\n", itemCode, itemName, pricepu, stock);
printf("\n");
printf("\n");
priceint = strtod(pricepu, (char **)NULL);
printf(" How many would you like: ");
scanf("%d", &quantpurchase);
total = priceint * quantpurchase;
printf(" %.2lf\n", total);
for (i=0; i<maxitems; i++) {
taxitems[0][i] = itemCode[i];
printf(" %s", taxitems[0][0]); //HERE'S WHERE I NEED HELP
}
purchase();
}
}
}
}
}
It's not giving me my desired result. Basically say "AG001" is currently stored under the variable "itemCode", I want to move that into an array. Appreciate all the help I can get. Thanks.
taxitems[0][i] = itemCode[i];
You can't copy char arrays with simple assignment. You need to use the strcpy() function instead.
strcpy( taxitems[0][i], itemcode[i], strlen(itemcode[i]);
You will need to add
#include <string.h>
to your code. You can find the reference to strcpy() function here
Related
I am trying to store the values stored in a details.txt file into their appropriate place in a dynamically allocated struct. Am I doing something (that should be simple) incorrectly for this not to work? Is it necessary for me to use strtok and split by ','?
My details.txt reads:
mitch,8,1.78,burgers
murray,42,6.5,lasagna
travis,64,1.85,sushi
sam,12,1.94,bacon
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 256
typedef struct
{
char name[BUFFERSIZE];
int favnumber;
float height;
char favfood[BUFFERSIZE];
} Person;
void print_person(Person *p)
{
printf("name: %s\n", p->name);
printf("num: %d\nheight: %.2f\nfav. food: %s\n\n",
p->favnumber, p->height, p->favfood);
}
int count_lines(FILE *fp)
{
int nlines = 0;
char c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp))
{
if (c == '\n')
{
nlines++;
}
}
rewind(fp);
return nlines;
}
int main(void)
{
FILE *fp = fopen("details.txt", "r");
// count lines
int nlines = count_lines(fp);
printf("found %d lines\n\n",nlines);
Person *people = (Person*)malloc(nlines*sizeof(Person));
char buffer[BUFFERSIZE];
int i = 0;
while (fgets(buffer,BUFFERSIZE,fp) != NULL)
{
sscanf(buffer,"%s%d%f%s",people[i].name,
&(people[i].favnumber),
&(people[i].height),people[i].favfood);
print_person(&(people[i]));
i++;
}
printf("found %d people\n",i);
free(people);
fclose(fp);
}
Unfortunately, the current output of my program is:
found 4 lines
name: mitch,8,1.78,burgers
num: 0
height: 0.00
fav. food:
...
found 4 people
The problem is that the first %s parse the the whole line, and you need , in the format string to separate the fields. Not an issue here yet but I also used %[^,] for the last format string so it will not stop at the first space. Also added precision on the strings to avoid buffer overflows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 255
#define str(s) str2(s)
#define str2(s) #s
typedef struct
{
char name[BUFFERSIZE+1];
int favnumber;
float height;
char favfood[BUFFERSIZE+1];
} Person;
void print_person(Person *p)
{
printf("name: %s\n", p->name);
printf("num: %d\nheight: %.2f\nfav. food: %s\n\n",
p->favnumber, p->height, p->favfood);
}
int count_lines(FILE *fp)
{
int nlines = 0;
char c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp))
{
if (c == '\n') {
nlines++;
}
}
rewind(fp);
return nlines;
}
int main(void)
{
FILE *fp = fopen("details.txt", "r");
// count lines
int nlines = count_lines(fp);
printf("found %d lines\n\n",nlines);
Person *people = (Person*)malloc(nlines*sizeof(Person));
char buffer[BUFFERSIZE+1];
int i = 0;
while (fgets(buffer,BUFFERSIZE+1,fp) != NULL)
{
// Changed line, see formatting of %s
sscanf(buffer,
"%" str(BUFFERSIZE) "[^,],%d,%f,%" str(BUFFERSSIZE) "[^,]",
people[i].name,
&(people[i].favnumber),
&(people[i].height),people[i].favfood);
print_person(&(people[i]));
i++;
}
printf("found %d people\n",i);
free(people);
fclose(fp);
}
I'm currently working on a program that is suppose to read information from a text-file. The text-file contains a song list and I have created a struct that should be able to hold each song in a song list in my program.
I have divided the program in different files and they look something like this.
main.c
#include "FuncDek.h"
#include <locale.h>
#include <crtdbg.h>
int main()
{
//For swedish and check memory leak
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
setlocale(LC_ALL, "swedish");
//Create with starting size of 5
Song *ptr = (Song *)malloc(sizeof(Song) * 4);
int menuChoice = 0;
int nrOfSongs = 0;
//Read from file
readFromFile(ptr, &nrOfSongs);
system("pause");
do
{
system("cls");
menuChoice = menu();
switch (menuChoice)
{
case 1:
addSong(ptr, &nrOfSongs);
break;
case 2:
showList(ptr, nrOfSongs);
break;
case 0:
break;
default:
printf("\nFelaktigt val, försök igen\n");
system("pause");
break;
}
} while (menuChoice != 0);
free(ptr);
system("pause");
return 0;
}
FuncDek.h
#ifndef FUNCDEK
#define FUNCDEK
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char title[25];
char artist[25];
char year[4];
} Song;
int menu();
void addSong(Song *ptr, int *nrOfSongs);
void showList(Song *ptr, int nrOfSongs);
void readFromFile(Song *ptr, int *nrOfSongs);
#endif
and finally the FuncDek.c
#include "FuncDek.h"
#pragma warning(disable: 4996)
//Print all from list
void showList(Song *ptr, int nrOfSongs)
{
system("cls");
printf("Låtlista\n");
printf("-------------------------------\n");
for (int i = 0; i < nrOfSongs; i++)
{
printf("Title: %s", ptr[i].title);
printf("Artist: %s", ptr[i].artist);
printf("År: %s \n\n", ptr[i].year);
}
system("pause");
}
//Read from file
void readFromFile(Song *ptr, int *nrOfSongs)
{
FILE *fileOpen;
fileOpen = fopen("song.txt", "r+");
if (fileOpen == NULL)
{
printf("Something went wrong. Could't open file\n");
}
char line[100];
int counter = 0;
int nrOfSongsInList = 0;
/*Read all information to line*/
while (fgets(line, sizeof(line), fileOpen) != NULL)
{
if (counter == 0)
{
nrOfSongsInList = line[0] - '0';
counter++;
}
else if (counter % 2 == 1 && counter == 1)
{
strcpy(ptr[*nrOfSongs].title, line);
counter++;
}
else if (counter % 2 == 0)
{
strcpy(ptr[*nrOfSongs].artist, line);
counter++;
}
else if (counter % 3 == 0)
{
strcpy(ptr[*nrOfSongs].year, line);
counter = 1;
*nrOfSongs += 1;
}
}
fclose(fileOpen);
}
I can now read my text-file and store my songs in my stong struct and I have allocated memory for it.
My problems occure when I'm trying to use the showList function. I can print out the ptr[i].artist and ptr[i].title correct, but for some reason when I print the ptr[i].year it show the year + the title of the next song in the list.
My text-file looks like this and each row is ended with a '\n'.
4
Mr Tambourine Man
Bob Dylan
1965
Dead Ringer for Love
Meat Loaf
1981
Euphoria
Loreen
2012
Love Me Now
John Legend
2016
I can't understand why it prints out more than the year. I noticed that if I make the year array in my struct the same size as the other 2, the problem goes away. But I want to understand.
When I debugg in VS it says that it's stored the right values in the year arr.
Anyone know what I might have missed?
/* problem of qsorting
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUT "doc.txt"
#define OUTPUT "output.txt"
#define MAX_SIZE 500
typedef struct student // here I declare stuctures
{
char name[20];
int index;
int code;
int grade;
char surname[20];
} student;
int cmpfunc (const void * a, const void * b) // initial part of qsort
{
return ( *(char*)a - *(int*)b );
}
int main()
{
int i=0, m=0;
int number=0;
FILE *fo;
FILE *fi;
char file[]={INPUT};
char file1[]={OUTPUT};
fo = fopen(file, "r"); // open the file
fi = fopen(file1, "w"); // open the file
student *studentPtr;
studentPtr = (student*) malloc(MAX_SIZE*sizeof(student));
// here I use mallocation
if(fo == NULL || studentPtr == NULL || fi == NULL)
{
perror("Error");
exit(1);
}
while (!feof(fo)) // reading of file
{
fscanf(fo,"%d %s %s %d %d",
&studentPtr[i].index,
studentPtr[i].name,
studentPtr[i].surname,
&studentPtr[i].code,
&studentPtr[i].grade);
i++;
}
i=m;
printf("please insert a number upto 7:\n");
// because there are only 7 raws in the file
scanf("%d",&number);
m=number;
if (number > 7)
{
printf("try again");
}
else
{
for(i=0;i<m;i++)
{
qsort(studentPtr[i].surname, 1, sizeof(char), cmpfunc); // ?
printf("%d %s %s %d %d\n", // printing out
studentPtr[i].index,
studentPtr[i].name,
studentPtr[i].surname,
studentPtr[i].code,
studentPtr[i].grade);
fprintf(fi,"%d %s %s %d %d\n", // writing in the file
studentPtr[i].index,
studentPtr[i].name,
studentPtr[i].surname,
studentPtr[i].code,
studentPtr[i].grade);
}
}
free(studentPtr);
fclose(fo);
fclose(fi);
return 0;
}
I am just beginner and sorry for obvious mistakes.
I cannot do qsorting properly.
i will attach txt file as a comment of this post.
could you guys tell me how to change first part of qsort not to get silly things, after that i will try to do that by myself
I'm having real trouble working with strings and string arrays, and using strcpy correctly. I'm using a dictionary of words scanned in a 2D array dictionary. Then I take a start word, alter every letter of it to create many different variants, i.e cat -> cbt, cct, cdt, etc. From there I copy each generated word into a 2D array and to compare these generated words to the dictionary to see if they are real words. I then want to print these real words, i.e cat as a start word will generate bat if its in the dictionary, but zat won't be. When I run the code it prints all the generated words but when It gets to check_dictionary function it prints no words.
The text file it reads from is like:
mat
yes
cat
hat
The code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_WORDS 20000
#define MAX_WORD_LENGTH 30
#define ARGS_REQUIRED 2
typedef struct scanned_words
{
char startword[MAX_WORD_LENGTH];
char endword[MAX_WORD_LENGTH];
} Scanned_words;
Scanned_words scan_two_words(Scanned_words words);
void get_next_word(Scanned_words words,
char parentwords[MAX_WORDS][MAX_WORD_LENGTH]);
void read_file(char * argv[], char dictionary[MAX_WORDS][MAX_WORD_LENGTH]);
void check_dictionary(char dictionary[MAX_WORDS][MAX_WORD_LENGTH],
char parentwords[MAX_WORDS][MAX_WORD_LENGTH]);
void usage(char * argv[]);
int main(int argc, char * argv[])
{
char dictionary[MAX_WORDS][MAX_WORD_LENGTH];
char nextword[MAX_WORDS][MAX_WORD_LENGTH];
char parentwords[MAX_WORDS][MAX_WORD_LENGTH];
Scanned_words words;
if (argc == ARGS_REQUIRED)
{
system("clear");
read_file(&argv[1], dictionary);
words = scan_two_words(words);
get_next_word(words, parentwords);
check_dictionary(dictionary, parentwords);
}
else
{
usage(&argv[0]);
}
return 0;
}
void read_file(char * argv[], char dictionary[MAX_WORDS][MAX_WORD_LENGTH])
//reads the text file and stores the dictonary as a 2D array
{
FILE * file_name;
int word_count = 0, i;
if ((file_name = fopen(argv[0], "r")) == NULL )
{
printf("Cannot open file ... \n");
}
while (fscanf(file_name, "%s", dictionary[i++]) == 1)
{
printf("%s ", dictionary[word_count]);
word_count++;
}
printf("\n");
printf("\n%d words scanned in from: %s\n\n", word_count, argv[0]);
}
Scanned_words scan_two_words(Scanned_words words)
//takes an empty structure, scans both words in and returns them in the same structure
{
printf("Enter the start word: \n");
scanf("%s", words.startword);
printf("\nEnter the end word: \n");
scanf("%s", words.endword);
printf("\n");
return words;
}
void get_next_word(Scanned_words words,
char parentwords[MAX_WORDS][MAX_WORD_LENGTH])
//get all eligible second words from original start word
{
char character;
char currentword[MAX_WORD_LENGTH];
int i;
strcpy(currentword, words.startword);
for (i = 0; currentword[i] != '\0'; i++)
{
strcpy(currentword, words.startword);
for (character = 'a'; character <= 'z'; character++)
{
currentword[i] = character;
strcpy(parentwords[i], currentword);
printf("%s ", parentwords[i]);
}
}
parentwords[i][0] = '\0';
printf("\n\n");
}
void check_dictionary(char dictionary[MAX_WORDS][MAX_WORD_LENGTH],
char parentwords[MAX_WORD_LENGTH][MAX_WORD_LENGTH])
//checks a generated word for eligibility against the dictionary, prints next generation words
{
int i, j;
printf("\nSecond words: \n\n");
for (j = 0; parentwords[j][0] != '\0'; j++)
;
{
for (i = 0; dictionary[i][0] != '\0'; i++)
{
if ((strcmp(dictionary[i], parentwords[j])) == 0)
{
printf("%s \n", parentwords[j]);
}
}
}
}
void usage(char * argv[])
//prints error message
{
printf("Incorrect usage, try: ./program_name %s\n", argv[1]);
}
The formatting revealed this:
for (j = 0; parentwords[j][0] != '\0'; j++)
;
which most probably was meant to be:
for (j = 0; parentwords[j][0] != '\0'; j++)
Here
while (fscanf(file_name, "%s", dictionary[i++]) == 1)
the i is used uninitialised
So change it definition to include an initialisation:
int word_count = 0, i = 0;
I'm practicing on structures, dynamic memory and file I/O but I can't understand what is wrong with this code. I suspect that the error is with realloc function. When I run the program after the file opening, the program crash.
I check a lot of times and I suppose that is not a syntax related problem(especially with realloc).
Structure declaration:
#define MAXLENPATH 250
#define MAXSTRING 25
typedef struct
{
int ID;
char Name[MAXSTRING];
char Surname[MAXSTRING];
char code[MAXSTRING];
int age;
}person;
Function to get record info:
#include <stdio.h>
#include <stdlib.h>
#include "Data.h"
#include "DataBase.h"
void initRecord(person *Person)
{
printf("Insert ID:\n");
scanf("%d", &Person->ID);
printf("Insert Name:\n");
scanf("%s", Person->Name);
printf("Insert Surname:\n");
scanf("%s", Person->Surname);
printf("Insert Age:\n");
scanf("%d", &Person->age);
printf("Insert code:\n");
scanf("%s", Person->code);
}
Main function:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "Data.h"
#include "DataBase.h"
int main(void) {
FILE *ts;
char *fpath=NULL;
int pCount=1; //variable to hold database records count
int i=0;
int toAdd=0;
person *personDB=NULL;
fpath="C:\\Users\\Pio\\Desktop\\FILEOP\\MYTXT.txt";
personDB = malloc(pCount*sizeof(person));
//fill the database(in memory)
i=0;
while( i < pCount)
{
printf("Record %d\n",i+1);
initRecord(&personDB[i]); //fill i-th database record
printf("Record %d ID:%d Name:%s Surname:%s Age:%d Code:%s \n", i+1, personDB[i].ID, personDB[i].Name, personDB[i].Surname, personDB[i].age, personDB[i].code );
i++;
if(i == pCount) // check if all records are filled, then ask to user how many records wants and realloc new memory
{
printf("Insert element to add to database records:");
scanf("%d", &toAdd);
personDB=realloc(personDB, toAdd*(sizeof(person)) );
pCount += toAdd;
}
}
//Print structure on file
if ((ts=fopen(fpath, "w")) != NULL)
{
puts("FILE OPENED");
fprintf(ts,"************INFO****************\n");
i=0;
while (i < pCount)
{
fprintf(ts, "Record %d ID:%d Name:%s Surname:%s Age:%d Code:%s \n", i+1, personDB[i].ID, personDB[i].Name, personDB[i].Surname, personDB[i].age, personDB[i].code );
i++;
}
fclose(ts);
}
else
perror("ERROR:");
system("pause");
return EXIT_SUCCESS;
}