1 year ago
#345641
Amilio
how to open and read a file in c++
PROBLEM SOLVED! Solution found thanks to Debaug in the comments section. Thank you all for helping.
!!!! Update: I added the function perror() inside my check function and it tells me "no such file or directory". So I am pretty sure that my problem comes from where my file is stored. As said in the comments, the file probably isn't in the projects root directory. However I have no idea how to access the root directory. !!!!
I am new to c++ and to programming in general. My problem is very basic but none of the existing answers found on the web worked for it.
I am trying to open a file stored on my computer and to extract the data from it. Here is my code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <cstdio>
using namespace std;
int main()
{
// Naming the variables
float Grade;
float Total;
float Grade_In_Percentage;
ifstream inData;
// Opening the file
inData.open("test.txt");
if(inData.fail())
{
cout << "Fail: Cannot open the file" << endl;
perror(0)
return 1;
}
// Extracting the data
cin >> Grade >> Total;
// Calculations
Grade_In_Percentage = Grade * 100 / Total;
// Display
cout << "Your grade in percentage is:" << setprecision(7) << Grade_In_Percentage << endl;
Grade_In_Percentage = ceil(Grade_In_Percentage);
cout << "round up:" << Grade_In_Percentage << endl;
if (Grade_In_Percentage < 50)
cout << "Fail" << endl;
else if (Grade_In_Percentage >= 60)
cout << "Need improvment" << endl;
else if (Grade_In_Percentage > 70)
cout << "Good" << endl;
else if (Grade_In_Percentage > 80)
cout << "Well done" << endl;
else if (Grade_In_Percentage > 90)
cout << "Excellent" << endl;
return 0;
}
As a result, I get "Fail: Cannot open the file".
What could I do?
c++
xcode
file-io
ifstream
0 Answers
Your Answer