i'm making a program in C that let the user insert the number of names that he wants, this names is stored in a global array and then they are printed, but the program finishes before, specifically when i try to access to the global array to print the names to show them to the user. I need to have my global array as follows: char *array[10]. This problem just happens when i use the previus syntax, but when i use: char array[10][], all runs fine, what's the problem here? somebody can help me please, i have tried so many hours.
CODE:
#include <stdio.h>
#define MAX 10
int counter = 0;
char *concts[MAX];
void add_2(char *name){
printf("Se anadira un elemento en el index %d\n", counter);
concts[counter] = name;
counter++;
}
void main(){
char *name;
int ingresando = 1, i;
do{
printf("ingresa un nombre: ");
scanf("%s", &name);
add_2(name);
printf("Seguir ingresando? ");
scanf("%d", &ingresando);
}while(ingresando == 1);
printf("Terminado. contador: %d\n", counter);
for(i = 0; i < counter; i++){
char *otherName = concts[i];
printf("%s\n", otherName);
}
}
PROBLEM:
I don't really know, but the program ends before what is expected, it compiles well and does not prompt errors.
EDIT:
The program stops after print "Terminado. contador: %d\n"
Here I made some changes
#include <stdio.h>
#include <string.h>
#define MAX 10
int counter = 0;
char concts[MAX][20];
void add_2(char *name){
printf("Se anadira un elemento en el index %d\n", counter);
strcpy(concts[counter], name);
counter++;
}
int main(){
char name[20];
int ingresando = 1, i;
do{
printf("ingresa un nombre: ");
scanf("%s", name);
add_2(name);
printf("Seguir ingresando? ");
scanf("%d", &ingresando);
}while(ingresando == 1);
printf("Terminado. contador: %d\n", counter);
for(i = 0; i < counter; i++){
char *name = concts[i];
printf("%s\n", name);
}
return 0;
}
Now run it.
#include <stdio.h>
#include <string.h>
void add_2(char *name); //defining prototype of function
#define MAX 10
int counter = 0;
char concts[MAX][20];
void add_2(char *name){
printf("Se anadira un elemento en el index %d\n", counter);
strcpy(concts[counter], name);
counter++;
}
main(){
char name[20];
int ingresando = 1, i;
do{printf("ingresa un nombre: ");
scanf("%s", &name);
add_2(name);
printf("Seguir ingresando? ");
scanf("%d", &ingresando);
}while(ingresando == 1);
printf("Terminado. contador: %d\n", counter);
for(i = 0; i < counter; i++){
char *name = concts[i];
printf("%s\n", name);
}
}
The above answers seem right but the other way is using malloc.
first you must include <stdlib.h> and then edit line 12(char *name) like this
char *name=malloc(21);
*for old version of gcc you must cast the output of malloc to char *
Related
I am building a small program that takes name and age as input (stored in a struct) and spits out the output. One of the problems that I am facing is I have to enter the number of people I am going to store, something that I am sure I can solve with realloc() it's just not working. Here is what I got so far.
#include <stdio.h>
#include<stdlib.h>
struct info
{
int age;
char name[30];
};
int main()
{
struct info *Ptr;
int i, num;
printf("Enter number of people");
scanf("%d", &num);
// Allocates the memory for num structures with pointer Ptr pointing to the base address.
Ptr = (struct info*)malloc(num * sizeof(struct info));
for(i = 0; i < num; ++i)
{
printf("Enter name and age:\n");
scanf("%s %d", &(Ptr+i)->name, &(Ptr+i)->age);
}
for(i = 0; i < num ; ++i)
printf("Name = %s, Age = %d\n", (Ptr+i)->name, (Ptr+i)->age);
return 0;
}
I have tried to realloc inside the first for loop, but it wasn't working even if it makes sense to have it there. Have also tried to convert the loop to a while loop like this:
while(input != "stop)
{
allocate more memory
}
How can I use realloc to in order to skip having to enter the persons number before entering them?
realloc is the correct way. Just start with Ptr = NULL and num = 0 and on each input increase the number of elements by one.
Remember to limit the number of characters scanf can read, otherwise you may buffer overrun.
Also I find Ptr[i] way easier then (Ptr+i)->.
Also compare strings with strcmp not using !=. The != will compare pointers to strings, not strings themselves.
As I like reading the whole line, then scanning the line, I would do it like this:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
struct info
{
int age;
char name[30];
};
int main()
{
struct info *ptr = 0;
size_t num = 0;
for (;;) {
printf("Enter name and age. If you want to stop, type only 'stop'.\n");
char line[256];
if (fgets(line, sizeof(line), stdin) == NULL) {
fprintf(stderr, "fgets error");
exit(-1);
}
if (!strcmp("stop\n", line)) {
break;
}
struct info tmp;
if (sscanf(line, "%29s %d\n", tmp.name, &tmp.age) != 2) {
fprintf(stderr, "error parsing line\n");
exit(-1);
}
ptr = realloc(ptr, (num + 1) * sizeof(*ptr));
if (ptr == NULL) {
fprintf(stderr, "error allocating memory!\n");
exit(-1);
}
ptr[num] = tmp;
++num;
}
for (size_t i = 0; i < num ; ++i) {
printf("Name = %s, Age = %d\n", ptr[i].name, ptr[i].age);
}
free(ptr);
return 0;
}
If you are not sure of the no.of.elements you want to allocate and do it based on the users choice, then you can follow the below approach.
It starts with one element and the memory is reallocated as when the user wants to add new element.
#include <stdio.h>
#include<stdlib.h>
struct info
{
int age;
char name[30];
};
int main()
{
struct info *Ptr=NULL;
int i=0, num;
char c='Y';
while(c=='Y'||c=='y') {
Ptr=realloc(Ptr,(i+1)*sizeof(struct info));
if(Ptr==NULL)
break;
printf("Enter name and age:\n");
scanf("%s %d",&Ptr[i].name,&Ptr[i].age);
printf("Do you want to cont?\n");
scanf(" %c",&c);
i++;
}
num=i;
for(i = 0; i < num ; ++i)
printf("Name = %s, Age = %d\n", (Ptr+i)->name, (Ptr+i)->age);
free(Ptr);
return 0;
}
To answer exactly, you can first read the input to temp variables and check if you need to stop: Break the loop if so. Or continue and reallocate the 'storage' array by increasing it's size by one and copying the values you just read to the 'storage' array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct info
{
int age;
char name[30];
};
int main()
{
struct info * infos = 0;
int num = 0;
char input_name[30];
int input_age;
while (1)
{
printf("Enter name and age:\n");
int r = scanf("%29s", input_name);
if (r == EOF || strcmp(input_name, "stop") == 0)
break;
scanf(" %d", &input_age);
infos = realloc(infos, sizeof(struct info) * (num + 1));
infos[num].age = input_age;
memcpy(infos[num].name, input_name, sizeof(char) * 30);
num++;
}
for(int i = 0; i < num ; ++i)
printf("Name = %s, Age = %d\n", infos[i].name, infos[i].age);
return 0;
}
You should use a data struct like vector.
vector_init init vector.
vector_push push val to vector, if necessary, will realloc memory.
vector_output output the vector.
The following code could work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INIT_SIZE 1
struct info
{
int age;
char name[30];
};
struct vector {
struct info* p;
int n;
int index;
};
void vector_init(struct vector* ve) {
ve->n = INIT_SIZE;
ve->index = 0;
ve->p = malloc(sizeof(struct info) * ve->n);
}
void vector_push(struct vector* ve, struct info* tmp) {
if (ve->n == ve->index) {
ve->n *= 2;
ve->p = realloc(ve->p, sizeof(struct info) * ve->n);
}
ve->p[ve->index++] = *tmp;
}
void vector_output(const struct vector* ve) {
for (int i = 0; i < ve->index; ++i)
printf("Name = %s, Age = %d\n", ve->p[i].name, ve->p[i].age);
}
int main()
{
struct vector ve;
vector_init(&ve);
for (;;) {
struct info tmp;
printf("Enter name and age:\n");
scanf("%29s", tmp.name);
if (strcmp(tmp.name, "stop") == 0)
break;
scanf("%d", &tmp.age);
vector_push(&ve, &tmp);
}
vector_output(&ve);
return 0;
}
I have to write a program only using things that i've learned in class, where I register information from a car, sort it and use the Binary Search to search for a cars' license plate. If the license plate is found, print all the info about that especific car, If don't pritnt "Not found" and returns -1. All works fine until the Binary Search, the problem is that it won't find the license plate, It always returns -1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CARRO 5 // DEFINE TAMANHO DA STRUCT
typedef struct // STRUCT
{
char placa[50];
char marca[50];
char modelo[50];
char ano[50];
char valordiaria[50];
} carro;
carro car[MAX_CARRO];
int compare (const void * a, const void * b)
{
carro *carroA = (carro *)a;
carro *carroB = (carro *)b;
return strcmp(carroA, carroB);
}
int main()
{
int x=0; //COUNTER
for(x=0; x<MAX_CARRO; x++) // CAR REGISTER
{
printf("\nCarro: %d", (x+1));
printf("\nPlaca: ");
scanf("%s",car[x].placa);
printf("Marca: ");
scanf("%s",car[x].marca);
printf("Modelo: ");
scanf("%s",car[x].modelo);
printf("Ano: ");
scanf("%s",car[x].ano);
printf("Valor da diaria: ");
scanf("%s",car[x].valordiaria);
}
qsort (car, MAX_CARRO, sizeof(carro), compare); // USO DO QSORT
printf("\n\nSTRUCT ORDENADA: \n");
for(x=0; x<MAX_CARRO; x++) // MOSTRA NA TELA A STRUCT ORDENADA
{
printf("\n\n\nCarro: %d", (x+1));
printf("\nPlaca: %s", car[x].placa);
printf("\nMarca: %s", car[x].marca);
printf("\nModelo: %s", car[x].modelo);
printf("\nAno: %s", car[x].ano);
printf("\nValor da diaria: %s", car[x].valordiaria);
}
char k[10];
// *****BINARY SEARCH******
printf("\n\n\n*****BUSCA DE PLACAS*****\n\n\n\n");
printf("Digite a placa que deseja procurar: \n");
scanf("%s", &k);
// ***PROBLEM***
int low, high, mid;
low=0;
high = MAX_CARRO-1;
while(low<=high)
{
mid = (low+high)/2;
if (strcmp(k, car[mid].placa)<0)
high=mid-1;
else if (strcmp(k, car[mid].placa)>0)
low=mid+1;
else
{
printf("\nPlaca: %s", car[mid].placa);
printf("\nMarca: %s", car[mid].marca);
printf("\nModelo: %s", car[mid].modelo);
printf("\nAno: %s", car[mid].ano);
printf("\nValor da diaria: %s", car[mid].valordiaria);
}
printf("\n\n****Not found****\n\n\n");
return -1; //
}
}
You have few bugs.
First one is in your compare() function. You can not write this line
return strcmp(carroA, carroB);
Because strcmp is working just with char* types, and carroA and carroB are of type carro*. You should place
return strcmp(carroA->placo, carroB->placo);
Now you will sort your structures by the value of placo.
Now lets take a look at your main function.
First bug in main() is in your line of code
scanf("%s", &k);
You don't need &, you should make it like this
scanf("%s",k);
Second bug is in your while() loop in the last line
return -1;
This is a huge thing because main() will return -1. If you want main() to exit like an error occurred you should write return 1;
Maybe you should use one variable to determine weather you have found what you was looking for in your binary search
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CARRO 5 // DEFINE TAMANHO DA STRUCT
typedef struct // STRUCT
{
char placa[50];
char marca[50];
char modelo[50];
char ano[50];
char valordiaria[50];
} carro;
carro car[MAX_CARRO];
int compare (const void * a, const void * b)
{
carro *carroA = (carro *)a;
carro *carroB = (carro *)b;
return strcmp(carroA->placa, carroB->placa);
}
int main()
{
int x=0; //COUNTER
for(x=0; x<MAX_CARRO; x++) // CAR REGISTER
{
printf("\nCarro: %d", (x+1));
printf("\nPlaca: ");
scanf("%s",car[x].placa);
printf("Marca: ");
scanf("%s",car[x].marca);
printf("Modelo: ");
scanf("%s",car[x].modelo);
printf("Ano: ");
scanf("%s",car[x].ano);
printf("Valor da diaria: ");
scanf("%s",car[x].valordiaria);
}
qsort (car, MAX_CARRO, sizeof(carro), compare); // USO DO QSORT
printf("\n\nSTRUCT ORDENADA: \n");
for(x=0; x<MAX_CARRO; x++) // MOSTRA NA TELA A STRUCT ORDENADA
{
printf("\n\n\nCarro: %d", (x+1));
printf("\nPlaca: %s", car[x].placa);
printf("\nMarca: %s", car[x].marca);
printf("\nModelo: %s", car[x].modelo);
printf("\nAno: %s", car[x].ano);
printf("\nValor da diaria: %s", car[x].valordiaria);
}
char k[10];
// *****BINARY SEARCH******
printf("\n\n\n*****BUSCA DE PLACAS*****\n\n\n\n");
printf("Digite a placa que deseja procurar: \n");
scanf("%s", k);
// ***PROBLEM***
int low, high, mid;
low=0;
high = MAX_CARRO-1;
int found=0;
while(low<=high && !found)
{
mid = (low+high)/2;
if (strcmp(k, car[mid].placa)<0)
high=mid-1;
else if (strcmp(k, car[mid].placa)>0)
low=mid+1;
else
{
found = 1;
printf("\nPlaca: %s", car[mid].placa);
printf("\nMarca: %s", car[mid].marca);
printf("\nModelo: %s", car[mid].modelo);
printf("\nAno: %s", car[mid].ano);
printf("\nValor da diaria: %s", car[mid].valordiaria);
}
}
if(!found)
printf("\n\n****Not found****\n\n\n");
return 0; //
}
I am coding a song database. For now, the data of 2 songs are stored in a text file, one struct field per line. I would like to copy the content of the file line by line into an array, and I do not get why the program crashes after calling load(). Is it a problem related to fgets()? Or when I replace '\n' by '\0'?
Here are the interesting parts of the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "functions.h"
int main()
{
int menu;
bool exit = false;
/*char title[256];
char artist[256];
char album[256];*/
int year;
Song **songs = NULL; // base pointer to the array (of pointers to struct)
FILE *f; // pointer to a file structure
int n = 0; // height of array at the beginning (= number of pointers to struct)
int i;
f = fopen("database.txt", "r+");
if(f == NULL)
return 0;
count_songs_db(f, &n); // will modify n (height of array) according to the number of existing songs
printf("n = %d\n", n);
songs = (Song**)malloc(n*sizeof(Song));
load(f, songs, n);
// MENU
for(i = 0 ; i < n ; ++i)
free(songs[i]);
free(songs);
fclose(f);
return 0;
}
functions:
void count_songs_db(FILE *f, int *n) // calculate how many songs there are already in the database.
{
int c, n_lines = 0;
while ((c = getc(f)) != EOF)
if (c == '\n')
++n_lines; // count number of lines
*n = n_lines/6; // 1 song = 6 lines. Changes the height of array accordingly.
rewind(f); // go back to beginning of file, to be able to load the db
}
void load(FILE *f, Song **songs, int n) // load existing songs (in the file) into the array
{
int i;
for(i = 0 ; i < n ; ++i)
{
fgets(songs[i]->title, 256, f); // reads a line of text
songs[i]->title[strlen(songs[i]->title)-1] = '\0'; // to replace \n by \0 at the end // not working?
fgets(songs[i]->artist, 256, f);
songs[i]->title[strlen(songs[i]->artist)-1] = '\0';
fgets(songs[i]->album, 256, f);
songs[i]->title[strlen(songs[i]->album)-1] = '\0';
fscanf(f, "%d\n", &(songs[i]->year)); // use it like scanf
fgets(songs[i]->genre, 256, f);
songs[i]->title[strlen(songs[i]->genre)-1] = '\0';
fscanf(f, "%d:%d\n", &(songs[i]->length.m), &(songs[i]->length.s));
}
for(i = 0 ; i < n ; ++i)
{
printf("Title: %s\n", songs[i]->title);
printf("Artist: %s\n", songs[i]->artist);
printf("Album: %s\n", songs[i]->album);
printf("Year of release: %d\n", songs[i]->year);
printf("Genre: %s\n", songs[i]->genre);
printf("Length: %d:%d\n", songs[i]->length.m, songs[i]->length.s);
}
}
struct:
typedef struct Length {
int m, s;
} Length;
typedef struct Song {
char title[256];
char artist[256];
char album[256];
int year;
char genre[256];
Length length;
} Song;
Thanks for your help.
Edit: I modified the code to use a simple array of struct. Here is the add_song() function and save() function:
void add_song(Song *songs, int *n)
{
printf("Title: ");
read(songs[*n].title, MAX_SIZE); // another function is used instead of scanf(), so the user can enter string with spaces. Also more secure.
printf("Artist: ");
read(songs[*n].artist, MAX_SIZE);
printf("Album: ");
read(songs[*n].album, MAX_SIZE);
printf("Year of release: ");
songs[*n].year = read_long(); // still have to check the user inputs (ie. year has to be between 1900 and 2017)
printf("Genre: ");
read(songs[*n].genre, MAX_SIZE);
printf("Length: \nmin: ");
songs[*n].length.m = read_long();
printf("sec: ");
songs[*n].length.s = read_long();
++(*n);
}
void save(FILE *f, Song *songs, int n) // save song in file
{
fprintf(f, "%s\n%s\n%s\n%d\n%s\n%d:%d\n", songs[n-1].title, songs[n-1].artist, songs[n-1].album, songs[n-1].year, songs[n-1].genre, songs[n-1].length.m, songs[n-1].length.s); // use it like printf. Prints the data in the file.
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct Length {
int m, s;
} Length;
typedef struct Song {
char title[256];
char artist[256];
char album[256];
int year;
char genre[256];
Length length;
} Song;
void count_songs_db(FILE *f, int *n) // calculate how many songs there are already in the database.
{
int c, n_lines = 0;
while ((c = getc(f)) != EOF)
if (c == '\n')
++n_lines; // count number of lines
*n = n_lines / 6; // 1 song = 6 lines. Changes the height of array accordingly.
rewind(f); // go back to beginning of file, to be able to load the db
}
void load(FILE *f, Song *songs, int n) // load existing songs (in the file) into the array
{
int i;
for (i = 0; i < n; ++i)
{
fgets(songs[i].title, 256, f); // reads a line of text
songs[i].title[strlen(songs[i].title) - 1] = '\0'; // to replace \n by \0 at the end // not working?
fgets(songs[i].artist, 256, f);
songs[i].title[strlen(songs[i].artist) - 1] = '\0';
fgets(songs[i].album, 256, f);
songs[i].title[strlen(songs[i].album) - 1] = '\0';
fscanf(f, "%d\n", &(songs[i].year)); // use it like scanf
fgets(songs[i].genre, 256, f);
songs[i].title[strlen(songs[i].genre) - 1] = '\0';
fscanf(f, "%d:%d\n", &(songs[i].length.m), &(songs[i].length.s));
}
for (i = 0; i < n; ++i)
{
printf("Title: %s\n", songs[i].title);
printf("Artist: %s\n", songs[i].artist);
printf("Album: %s\n", songs[i].album);
printf("Year of release: %d\n", songs[i].year);
printf("Genre: %s\n", songs[i].genre);
printf("Length: %d:%d\n", songs[i].length.m, songs[i].length.s);
}
}
int main()
{
int menu;
bool exit = false;
/*char title[256];
char artist[256];
char album[256];*/
int year;
Song *songs = NULL; // base pointer to the array (of pointers to struct)
FILE *f; // pointer to a file structure
int n = 0; // height of array at the beginning (= number of pointers to struct)
int i;
f = fopen("database.txt", "r+");
if (f == NULL)
return 0;
count_songs_db(f, &n); // will modify n (height of array) according to the number of existing songs
printf("n = %d\n", n);
songs = (Song*)malloc(n * sizeof(Song));
load(f, songs, n);
// MENU
free(songs);
fclose(f);
return 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;
}
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