Structs and C-Strings

Alright so I have an assignment where I can basically only use functions from the string class and the basic objective of my program is to create an inventory within the program (A store inventory) that keeps track of itemIDs, name of item, producer, quantity. and such.

I'm not allowed to use classes/files.

So I have this code
1
2
3
4
5
6
7
8
9
10
11
12


void initialize(invType& inv){
   createItem (inv.items[0], "10300", "Nutella", "Ferrero", 10);
   createItem (inv.items[1], "10475", "Almonds", "Members Mark", 27);
   createItem (inv.items[2], "14310", "Peas & Carrots", "Libbys", 230);
   createItem (inv.items[3], "15730", "Tomato Paste", "Hunts", 400); 
   createItem (inv.items[4], "29500", "Cranberry Juice", "Ocean Spring", 85);
   createItem (inv.items[5], "30475", "Orange Juice", "Florida's Choice", 98);
   createItem (inv.items[6], "34330", "Eggs", "Centeral Market", 78);
   createItem (inv.items[7], "56900", "Eggs", "Eggland's Best", 100);  
   inv.total=8;          


given to me to use and I already created the initialize function and createItem function. However, a friend told me from there, I need to use strcpy to store the createItem stuff in the createItem function and I was wondering how I could do that. Thank you for your time :x.

And this is my struct (I just put it in random places just to see if my program would compile)

1
2
3
4
5
6
7
8
9
struct itemType{
char  ID[8];
char ProductName[20];
char Producers[20];
int Quantity;    
           };
struct invType{
itemType items[100];
int total;};
Last edited on
Wait, you are allowed to use std::string or are you only allowed to use functions found in <cstring> (like strcpy(), strcat(), etc)?

In your createItem() function, you can use strncpy() to copy the c-string:
http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

1
2
3
4
5
6
7
8
9
10
11
void createItem(
  struct itemType& item,
  const char*      ID,
  const char*      productName,
  const char*      producers,
  int              quantity
) {
  strncpy( item->ID,          ID,          7  );  item->ID[ 7 ]           = '\0';
  strncpy( item->ProductName, productName, 19 );  item->ProductName[ 19 ] = '\0';
  ...
}

Notice that there are a couple of caveats to using strncpy(), the most important of which is that you must specifically guarantee that the target string is null-terminated.

Hope this helps.
Thank you!
Topic archived. No new replies allowed.