I am having some issues. I was trying to use my setToolName function to copy the string into the array – this would check if the string was too long. But then it does not capture 2 words, say if the string is “lawn mower”. So I started to use getline and this works. The issue is it does not truncate the string if it is too long for the array. Below are my 2 functions and I was wondering how I could fix them to get this to work and to work efficiently:
void Tools::enterRecords()
{
fstream outTools( "hardware.dat", ios::in | ios::out | ios::binary );
// exit program if fstream cannot open file
if ( !outTools )
{
cerr << "File could not be opened." << endl;
exit( 1 );
} // end if
// require user to specify a tool identification number
cout << "Enter tool identification number (1 to 100, 0 to end input): ";
cin >> partNumber;
Tools tool; // create the object
// user enters information, which is copied into file
while (partNumber != 0)
{
validatePartNumber(partNumber);
// user enters tool name, quantity and unit price
cout << "Enter the tool name: ";
fflush(stdin);
cin.getline( toolName, 20, '\n' );
cout << "Enter the quantity in stock: ";
cin >> inStock;
cout << "Enter the unit price: ";
cin >> unitPrice;
// set the record for the part number, tool name, quantity in stock, and unit price
tool.setPartNumber( partNumber );
tool.setToolName( toolName );
tool.setInStock( inStock );
tool.setUnitPrice( unitPrice );
// seek position in file of user-specified record
outTools.seekp( ( tool.getPartNumber() - 1 ) * sizeof ( Tools ) );
// write user-specified information in file
outTools.write( reinterpret_cast < const char * >( &tool ),sizeof ( Tools) );
//enable user to enter another account
cout << "\nEnter tool identification number (1 to 100, 0 to end input): ";
cin >> partNumber;
} // end while loop
} // end enterRecords function
Specifically within this function:
// user enters tool name, quantity and unit price
cout << "Enter the tool name: ";
fflush(stdin);
cin.getline( toolName, 20, '\n' );
And then my setToolName function:
// set the tool name
void Tools::setToolName(string toolNameString)
{
// copy at most 20 characters for the tool name
const char *toolNameValue = toolNameString.data();
int length = int(toolNameString.size());
length = (length < 20 ? length : 19);
strncpy(toolName, toolNameValue, length);
//toolName[ length ] = '\0'; // append null character to lastName
}