您好,我的教授發佈這個例子到她的網站舉例說明ifstreams,我怎麼不能打開任何.txt文件?文件不會打開ifstream
#include <iostream>
#include <iomanip> // for setw
#include <fstream> // for ifstream, ofstream
using namespace std;
int main()
{
char filename[25]; // a string for filename entry
int val; // for reading integers from file
int sum = 0, count = 0;
double average;
ifstream in1; // create an input file stream
do
{
in1.clear();
cout << "Please enter the name of the input file.\n";
cout << "Filename: ";
cin >> setw(25) >> filename;
in1.open(filename);
if (!in1)
cout << "That is not a valid file. Try again!\n";
} while (!in1);
// PROCESS THE INPUT FILE
// Read all integer values and compute average
while (!in1.eof()) // while not end of file
{
in1 >> val; // read an integer from file
if (!in1.fail()) // in case last call failed to read an int
{ // due to trailing white space at end of file
count++;
sum += val;
}
}
average = static_cast<double>(sum)/count;
cout << "There were " << count << " numbers in the file\n";
cout << "Sum = " << sum << "\t\tAverage = " << average << "\n\n";
in1.close();
return 0;
}
這是非常加重的!這是我的電腦或其他問題嗎?
塊引用
歡迎來到Stack Overflow!我們需要更多信息來幫助您 - 運行此代碼時發生了什麼? – Kelm 2014-12-06 23:42:31
您是否嘗試過絕對路徑? – Borgleader 2014-12-06 23:44:14
當我運行代碼時,它提示我輸入文件名,但它告訴我它永遠找不到我輸入的文件 – Demomomo 2014-12-06 23:44:32