0
我的問題是在嘗試讀取文本文件時直接設置「failbit」。奇怪的是,至少對我來說,如果我構建我的程序並運行它,它就會起作用。但是,當我嘗試調試它的故障位集。ifstream在嘗試讀取文本文件時設置失敗位
實際的錯誤消息我得到的是這樣的:
「在Steg1_1A.exe在0x7740c41f未處理的異常:微軟C++異常:性病::的ios_base ::故障存儲器位置0x003bf8e4。」
而控制檯程序的文本是這樣的:「ios_base :: failbit set」。
問題是,我該如何修復,以便在調試時failbit不會「崩潰程序」?
這裏是我的功能:
void selectedMenuChoice(int choice)
{
int index = 0, initValue = 0;
const int fileNumberCount = 24;
double numFromFile = 0.0, sum = 0.0, average = 0.0, max = 0.0, min = 0.0;
switch (choice)
{
// "Display temperature values"
case 1:
cout << "\nDisplaying the latest 24 temperature values:\n\n";
break;
// "View maximum and minimum temperatures"
case 2:
cout << "\nCalculating the maximum and minimum temperature...\n";
break;
// "View average temperature"
case 3:
cout << "\nCalculating average temperature...\n";
break;
}
ifstream file;
file.exceptions(ifstream::failbit | ifstream::badbit);
try
{
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Here is the problem. It throws an exception directly when debugging
file.open("templog.txt"); // filnamnet
//file.fail();
// "View maximum and minimum temperatures"
if (choice == 2)
{
initValue = 1;
file >> numFromFile;
max = min = numFromFile;
}
// Loopar igenom filen dock baserat på ett konstantvärde.
for (index = initValue; index < fileNumberCount; index++)
{
file >> numFromFile;
switch (choice)
{
// "Display temperature values"
case 1:
if (index % 6 == 0)
{
cout << endl;
}
cout << fixed << setprecision(2) << setw(8) << numFromFile;
break;
// "View maximum and minimum temperatures"
case 2:
if (numFromFile > max)
{
max = numFromFile;
}
if (numFromFile < min)
{
min = numFromFile;
}
break;
// "View average temperature"
case 3:
sum += numFromFile;
average = sum/24;
break;
}
}
}
catch (ifstream::failure e)
{
//std::cerr << "Exception opening/reading file.";
cout << e.what(); // Skriver ut vad felet egentligen är..
}
file.close();
// Skriver ut information till användaren baserat på valet som användaren har gjort
if (choice == 2)
{
cout << "\nMaximum temperature: " << fixed << setprecision(2) << max <<" degrees Celcius\n";
cout << "\nMinimum temperature: " << min << " degrees Celcius\n";
}
else if (choice == 3)
{
cout << "\nAverage temperature: ";
cout << fixed << setprecision(2) << average << " degrees Celcius\n";
}
continueOnKeyPressed();
}
非常感謝Bo Persson先生! Hehe,gissar att duärsvensk。 :-)你是對的! – user2130009 2013-04-05 13:00:37
@BoPersson我認爲你應該讓這個答案。 – 0x499602D2 2013-04-05 16:12:06