我提交了這個程序,它的工作原理完美,但我的老師說我的while
循環出了問題,即使我得到了正確的答案。任何提示或幫助?循環讀取輸入的C++
當達到文件結尾且第43行的read
變得無效時,在while
循環中會發生什麼情況?你的程序的結構方式你沒有看到問題,但它在那裏。應該重構while
環路來解決這個問題。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream inputfile;
char choice;
int NumberOfIntegers = 0,
SumOfIntegers = 0,
Average = 0 ,
LargestValue,
SmallestValue,
integer;
inputfile.open("random.txt");
if(!inputfile)
{
cout << "the file could not be open" << endl;
}
inputfile >> integer;
//initialize smallest and largest
SmallestValue = integer;
LargestValue = integer;
while(inputfile)
{
NumberOfIntegers++;
SumOfIntegers = SumOfIntegers + integer;
inputfile >> integer;
if(integer > LargestValue || integer < SmallestValue)
{
if (integer > LargestValue)
LargestValue = integer;
else
SmallestValue = integer;
}
}
if(NumberOfIntegers > 0)
{
Average = SumOfIntegers/NumberOfIntegers;
}
//closing input file
inputfile.close();
do
{
//Display Menu
cout << "Make a selection from the list" << endl;
cout << "A. Get the largest Value" << endl;
cout << "B. Get the smallest Value" << endl;
cout << "C. Get the sum of the values" << endl;
cout << "D. Get the average of the values" << endl;
cout << "E. Get the number of values entered" << endl;
cout << "F. End this program" << endl << endl;
cout << "Enter your choice --> ";
cin >> choice;
cout << endl;
switch (choice)
{
case 'a':
case 'A': cout << "The largest value is " << LargestValue << endl;
break;
case 'b':
case 'B': cout << "The smallest value is " << SmallestValue << endl;
break;
case 'c':
case 'C': cout << "The sum of the values entered is " << SumOfIntegers << endl;
break;
case 'd':
case 'D': cout << "The average of the values entered is " << Average << endl;
break;
case 'e':
case 'E': cout << "The number of values entered is " << NumberOfIntegers << endl;
break;
case 'f':
case 'F': cout << "Program ending" << endl << endl;
cin.ignore();
cout << "\n\nPress Enter to end --> ";
cin.ignore();
return 0;
default:
cout << choice << " is an invalid value. " << endl;
}
cout << endl;
} while(choice != 'f' || choice != 'F');
return 0;
}
在使用該值之前,您從不檢查輸入是否成功。 – chris
你有一位好老師。 – 0x499602D2