我正在尝试将字符串值(“Appliance”,“Kitchenware”或“Tool”)添加到位于struct newItem中的C字符串数组“category [CATEGORY_SIZE]”,但是一旦用户尝试执行此操作,程序终止。如果我这样做不正确,有人可以解释为什么会这样以及如何正确存储字符串值吗?
#include <fstream>
#include <iostream>
#include <sstream>
#include <cctype>
using namespace std;
//Array sizes
const int CATEGORY_SIZE = 15, DATE_SIZE = 12;
//Declare structure for record
struct Item
{
int SKU;
string category[CATEGORY_SIZE];
int quantity;
double cost;
string date[DATE_SIZE];
};
int main()
{
//declare variables
int answer;
int cat;
int month;
string categoryChoice;
string monthChoice;
string theNumberString;
string theNewNumberString;
string fullDate;
int dayChoice;
int yearChoice;
char anotherRecord;
Item newItem; // to hold info about an item.
fstream dataFile;
fstream data("test.dat", ios::out | ios::binary);
cout << "This program allows you to store inventory data for appliances, kitchenware,
and tools in a file.";
while (true)
{
cout << "What would you like to do? :\n\n";
cout << "1. Add new records to the file\n";
cout << "2. Display a record in the file\n";
cout << "3. Change any record in the file\n";
cout << "4. Display total wholesale value of a particular item inventory.\n";
cout << "5. Display total wholesale value of a particular category inventory.\n";
cout << "6. Display total quantity of all items in the inventory." << endl;
cout << "Please enter a number[1-6] or enter 0 to quit program: ";
cin >> answer;
if (answer == 0)
{
return 0;
}
if (answer < 0 || answer > 6)
cout << "That is not a valid response, please try again. ";
if (answer == 1)
{
while (true)
{
cout << "Enter the following data about an item: \n\n";
cout << "SKU Number (Stock Keeping Unit Number): ";
cin >> newItem.SKU;
cin.ignore(); //Skip over the remaining newline.
while (true)
{
cout << "Please enter what category the item falls in : \n";
cout << "1. Appliance \n" "2. Kitchenware \n" "3. Tool: \n" << endl;
cout << "Please enter a choice [1-3]: ";
cin >> cat ;
if (cat < 1 || cat > 3)
cout << "Invalid choice. Please select again." << endl;
else if (cat == 1)
{
newItem.category[CATEGORY_SIZE] = "Appliance";
break;
}
else if (cat == 2)
{
newItem.category[CATEGORY_SIZE] = "Kitchenware";
break;
}
else if (cat == 3)
{
newItem.category[CATEGORY_SIZE] = "Tool";
cout << newItem.category[CATEGORY_SIZE];
break;
}
}
}
}
答案 0 :(得分:1)
newItem.category[CATEGORY_SIZE] = "Appliance";
(同样):您有未定义的行为。您正在访问数组越界,因为索引属于[0, size)
范围。使用std::vector
以及push_back
或emplace_back
(取决于C ++ 11支持):
std::vector<std::string> category; //you can construct this with an initial size
...
newItem.category.push_back("Appliance");