안녕하세요. 교수님이 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;
}
이것은 매우 가중합니다! 그것은 내 컴퓨터 또는 뭔가 문제가 있습니까?
인용문
스택 오버플로에 오신 것을 환영합니다! 이 코드를 실행할 때 정확히 무엇이 발생합니까? – Kelm
절대 경로를 사용해 보셨습니까? – Borgleader
코드를 실행하면 파일 이름을 입력하라는 메시지가 표시되지만 입력 한 파일을 찾을 수 없다는 메시지가 표시됩니다. – Demomomo