我正在尝试创建一个程序,用户可以在其中输入数字量,用户选择(升序或降序)以及数字本身。然后它创建一个输入文件(“input.txt”),其中包含数字量,用户选择和数字本身。然后该文件通过一个函数传递,在该函数中它读取输入文件并创建一个输出文件(“output.txt”),其中包含数字的数量和排序后的数字。目前,当程序试图输入大小并且我不知道原因时,它会给我错误。我也读过Walter Savitch的Absolute C ++ for awnsers但是我找不到它说你可以让一个程序读取输入文件中的数字和字符。任何帮助或建议将不胜感激。所有代码都在下面。
void inputFile(int numbers[], char choice, int size)
{
ifstream inFile;
cout << "\n\n Creating input.txt"<<endl;
inFile.open("input.txt");
//checks if it fails to open
if(inFile.fail())
{
cout<<"Error#1: Input file failed to open";
exit(1);
}
cout<<"Inputing user choice and size"<<endl;
//Inputs choice and size into input.txt
inFile >> size >> "\n";
inFile >> choice >> "\n";
cout << "Iputing numbers"<<endl;
//inputs all the numbers
for(int x=0; x<size; x++)
{
inFile >> numbers[x] >> "\n";
}
outputFile(inFile);
cout << "Closing input file"<<endl;
inFile.close();
}
void outputFile(ifstream& inData)
{
ofstream outFile;
cout << "Creating output.txt"<<endl;
//creates the output.txt file
outFile.open("output.txt");
//check if it fails to open
if(outFile.fail())
{
cout<<"Error#2: Output file failed to open";
exit(1);
}
//initilizing variables
int n=0;
int *sort;
int next;
int size;
int totalTimesTrue;
char choice;
cout << "Reading size in input.txt"<<endl;
//takes the size and puts in in the output file
while(inData >> next)
{
if(next == '\n')
{
break;
}
size = next;
outFile << size<<"\n";
}
//creating a dynamic array
sort = new int[size];
cout << "Reading user choice"<<endl;
//reads the user choice from the input file. (a)scending or (d)escending
inData.get(choice);
if(choice = 'a')
{
cout<<"Sorting numbers in ascending order"<<endl;
while(inData >> next && n<size)
{
if(next == '\n')
{
continue;
}
sort[n]= next;
n++;
}
for(int x=0; x<size; x++)
{
totalTimesTrue=0;
for(int y=0; y<size; y++)
{
if(sort[x]<sort[y])
{
totalTimesTrue++;
}
}
sort[totalTimesTrue]=sort[x];
}
}
else if(choice = 'd')
{
cout <<"Sorting numbers in decending order"<<endl;
while(inData >> next && n<size)
{
if(next == '\n')
{
continue;
}
sort[n]=next;
n++;
}
for(int x=0; x<size; x++)
{
totalTimesTrue=0;
for(int y=0; y<size; y++)
{
if(sort[x]>sort[y])
{
totalTimesTrue++;
}
}
sort[totalTimesTrue]=sort[x];
}
}
cout<<"Creating the output"<<endl;
for(int x=0; x<size; x++)
{
outFile << sort[x] << "\n";
}
delete sort;
cout<<"Closing output.txt"<<endl;
outFile.close();
}