以下程序基本上要求输入文件,然后将结果写入输出文件。当我编译它时,它在VisualStudio中没有显示任何错误。
当程序运行并要求输入文件时,我输入输入文件并点击进入程序,只需用闪烁的光标坐在那里。它没有进一步发展。我无法弄清楚我的生活是怎样的。
更新:当使用调试器并单步执行“SalesRecord_Array read_records(ifstream& in,int& n)”时,我在本地人中遇到以下错误:
标头文件(sort.h):
#ifndef SORT_H
#define SORT_H
//A generic sorting function.
template<class T>
void sort(T a[], int number_used);
//Precondition: number_used <= declared size of the array a.
//The array elements a[0] through a[number_used - 1] have values.
//Postcondition: The values of a[0] through a[number_used - 1] have
//been rearranged so that a[0] <= a[1] <= ... <= a[number_used - 1].
template<class T>
void swap_values(T& variable1, T& variable2);
//Interchanges the values of variable1 and variable2.
template<class T>
int index_of_smallest(const T a[], int start_index, int number_used);
//Precondition: 0 <= start_index < number_used. Array elements have values.
//Returns the index i such that a[i] is the smallest of the values
//a[start_index], a[star_index + 1], ..., a[number_used - 1].
template<class T>
void sort(T a[], int number_used)
{
int index_of_next_smallest;
for (int index = 0; index < number_used - 1; index++)
{//Place the correct value in a[index]:
index_of_next_smallest =
index_of_smallest(a, index, number_used);
swap_values(a[index], a[index_of_next_smallest]);
//a[0] <= a[1] <=...<= a[index] are the smallest of the original array
//elements. The rest of the elements are in the remaining positions.
}
}
template<class T>
void swap_values(T& variable1, T& variable2)
{
T temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
template<class T>
int index_of_smallest(const T a[], int start_index, int number_used)
{
T min = a[start_index];
int index_of_min = start_index;
for (int index = start_index + 1; index < number_used; index++)
if (a[index] < min)
{
min = a[index];
index_of_min = index;
//min is the smallest of a[start_index] through a[index]
}
return index_of_min;
}
#endif
源文件(source.cpp):
#include <iostream>
#include <fstream> // For I/O
#include <iomanip> // For setw()
#include <cstdlib> // For system()
#include <string> // For stricmp()
#include "sort.h" // Generic sort() function
using namespace std;
const int MAX_FILE_NAME = 35; // Maximum file name length
const int MAX_ID_LEN = 10; // Maximum length for items's id
const int MAX_NAME_LEN = 30; // Maximum length for itemsloyee's name
const double DISCOUNT = 0.10; // Quantity sold value at which commision rate changes
const double DISCOUNT_BREAK_POINT = 10; // Regular commission per subscription sold
class SalesRecord // Record definition for items's sales record
{
private:
char item_id[MAX_ID_LEN + 1]; // Items's id
char item_name[MAX_NAME_LEN + 1];// Items's name
int quantity_sold; // Number of magazine subscriptions sold
double regular_price; // Commission on each subscription
double discount_price; // Salesperson's commission
double total_price; // Total price of items
public:
// Functions that operate on an individual record
void read(ifstream& in); // Read record from input stream
void calc_discount_price(); // Calculate commission fields in record
void write(ostream & os) const; // Write record to output stream
int operator<(const SalesRecord& right) const;// Overloaded for use in sort
};
typedef SalesRecord * SalesRecord_Array; // Used to allocate 1-D sales record array
// Utility functions - functions are not specific to this problem
void open_input(ifstream& input, char name[]); // Get file name & Open file
void open_output(ofstream& output, char name[]); // Get file name & Open file
// Funcions that operate on array (set) of records
SalesRecord_Array read_records(ifstream& in, int &n); // Allocate space for records & read them
void calc_discounts(SalesRecord_Array records, int n); // Calculate commission rate and commission
void write_records(SalesRecord_Array records, int n); // Save records to file
int main()
// Parameters: None
// Returns: Zero
// Calls: open_input(), read_records(), calc_commissions(), sort(), write_records().
{
char again; // Does user want to go through loop again?
int num_records; // # of records
char infilename[MAX_FILE_NAME + 1]; // Name of file for records to be processed
ifstream in; // Input file stream
SalesRecord_Array records = NULL; // Pointer to array of sales records
do
{
open_input(in, infilename); // Get file name & open file
records = read_records(in, num_records); // Read records & get number of records
in.close(); // Close file
if (num_records > 0)
{
calc_discounts(records, num_records); // Calculate commission values for each record
sort(records, num_records); // Sort records by item name
write_records(records, num_records); // Save records to new file
delete[] records; // Free array of records
}
else
{
cout << "\n\n\aNo data in file: " << infilename << endl;
}
cout << "\nDo you want to process another file (Y/N)? ";
cin >> again;
cin.ignore(256, '\n'); // Remove Enter key from keyboard buffer
} while (again == 'y' || again == 'Y');
cout << "\n\n***** END OF PROGRAM ******\n";// Print closing message.
return 0;
} // End of main()
// Utility functions
void open_input(ifstream& input, char name[]) //Open file
// Parameters: Variables for input file reference nad input file name
// Returns: None
// Calls: None
{
int count = 0; // Count number of tries
do // Continue until we get a valid file name and can open file
{
count++;
if (count != 1) // Issue error message if we are trying again.
{
cout << "\n\aInvalid file name or file does not exist. Please try again."
<< endl;
}
cout << "\nEnter the input file name (maximum of " << MAX_FILE_NAME
<< " characters please)\n:> ";
cin.get(name, MAX_FILE_NAME + 1);// Gets at most MAX_FILE_NAME characters
cin.ignore(256, '\n'); // Remove Enter key from keyboard buffer
input.clear(); // Clear all error flags, if any, from prev try
input.open(name, ios_base::in); // Open only if file exists
} while (input.fail()); // If can't open file, try again
} // End of open_input()
void open_output(ofstream& output, char name[]) //Open file
// Parameters: Variables for output file reference and output file name
// Returns: None
// Calls: None
{
int count = 0; // Count number of tries
do // Continue until we get a valid file name and can open file
{
count++;
if (count != 1) // Issue error message if we are trying again.
{
cout << "\n\aInvalid file name. Please try again."
<< endl;
}
cout << "\nEnter the output file name (maximum of " << MAX_FILE_NAME
<< " characters please)\n:> ";
cin.get(name, MAX_FILE_NAME + 1);// Gets at most MAX_FILE_NAME characters
cin.ignore(256, '\n'); // Remove Enter key from keyboard buffer
output.clear(); // Clear all error flags, if any, from prev try
output.open(name); // Open file for output
} while (output.fail()); // If can't open file, try again
} // End of open_output()
void SalesRecord::read(ifstream& in) // Read record from input stream, does not read commission values
// Parameters: Input stream
// Returns: none
// Calls: None
{
in.get(item_id, MAX_ID_LEN + 1); // Read id
while (in.get() != '\n'); // Clear Enter after id
in.get(item_name, MAX_NAME_LEN + 1); // Read name: Last, First
while (in.get() != '\n'); // Clear Enter after name
in >> quantity_sold >> regular_price; // Read quantity sold value
while (in.get() != '\n'); // Clear Enter at end of record
} // End of SalesRecord::read()
void SalesRecord::calc_discount_price() // Calculate commission fields in record
// Parameters: None
// Returns: None
// Calls: None
{
double discount_rate;
if (quantity_sold < DISCOUNT_BREAK_POINT)
discount_rate = 0.0;
else
discount_rate = DISCOUNT;
discount_price = regular_price - (discount_rate * regular_price);
total_price = quantity_sold * discount_price;
} // End of SalesRecord::calc_commission()
void SalesRecord::write(ostream & os) const// Write record to output stream
// Parameters: Output stream, record to be written
// Returns : None.
// Calls : None.
{
os.setf(ios::fixed); os.setf(ios::showpoint); os.precision(2);
os << item_id << "\n" << item_name << "\n"
<< quantity_sold << " " << regular_price << " "
<< discount_price << " " << total_price << endl;
} // End of SalesRecord::write()
int SalesRecord::operator<(const SalesRecord& right) const
{
if (_stricmp(item_name, right.item_name) < 0)
return 1;
else
return 0;
} // End of SalesRecord::operator<
// Funcions that operate on array (set) of records
SalesRecord_Array read_records(ifstream& in, int &n) // Allocate space for records & read them
// Parameters: Input stream, variable for number of records.
// Returns : Pointer to array of records allocated.
// Calls : SalesRecord::read().
{
in >> n; // Read number of records
if (n < 1 || in.fail())
return NULL; // No records to read return
while (in.get() != '\n'); // Clear enter after number of records in file
SalesRecord_Array records; // Pointer for array of records
records = new SalesRecord[n]; // allocate space for records
if (records == NULL)
{
cout << "\aCan not allocate memory!";
exit(1);
}
int i;
for (i = 0; in.good() && !in.eof() && i < n; i++)
{
records[i].read(in); // Read each record
}
return records; // Return pointer to array
} // End of read_records()
void calc_discounts(SalesRecord_Array records, int n) // Calculate commission rate and commission
// Parameters: Array of records, number of records.
// Returns : None.
// Calls : SalesRecord::calc_commission().
{
int i;
for (i = 0; i < n; i++)
{
records[i].calc_discount_price(); // Process each record
}
} // End of calc_records()
void write_records(SalesRecord_Array records, int n) // Save records to file
// Parameters: Array of records, number of records.
// Returns : None.
// Calls : SalesRecord::write().
{
char outfilename[MAX_FILE_NAME + 1]; // Name of file for output records
ofstream out; // Output file stream
cout << "\n\nI need the output file name." << endl;
open_output(out, outfilename); // Get file name & open file
if (out.good())
{
out << n << endl; // Write number of records to file
int i;
for (i = 0; i < n; i++)
{
records[i].write(out); // Write each record to file
}
out.close();
}
else
{
cout << "\a\nUnable to save data!" << endl;
}
} // End of write_records()
输入文件(order.txt)
5
0-8053-7442-6
Problem Solving with C++
1 45.50
7751158146
Looney Tunes Diskettes
12 8.50
88869809780
HP Laser Printer Paper
3 10.99
2429412454
No. 2 Pencil
24 0.10
4895469286
Note Pad
5 0.89