Im new to c++ and i was trying to open a ".txt" file using ifstream. the file im using is called "ola.txt" which literally just contains two lines of text without punctuation just plain and simple text. The code that i wrote is this
#include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int x;
string line;
vector<int> vect;
ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt");
inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt");
if (inFile.is_open()) {
while (getline(inFile, line))
{
cout << line << '\n';
}
inFile.close();
}
else {
cout << "Unable to open file";
exit(1); // terminate with error
}
return 0;
}
The path to the file that i wrote is correct such that the file opens, but when the program runs it doesn´t cout the lines that i wrote on the txt file to the cmd, i dont know if this is somewhat important but im coding in visual studio 2019. I can't seem to find the answer to this problem anywhere in the internet and to be honest i think im doing it right, any help would be much appreciated,thanks in advance.
You are trying to open the inFile
twice. First time during inFile
construction, ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt")
, second time you try to open it again with inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt")
, when it's already open, which is erroneous, and flags the stream as no longer good.
3 possible fixes:
inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt")
inFile.close()
before you open it again (obviously, not the nicest fix).