0
Opening .txt files
How exactly would you open and read the contents of a text file? All I get are errors.
12 Answers
+ 11
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string line;
char input;
ifstream MyFile;
cout << "Do you want to read text file? (Y/N) : ";
cin >> input;
if (input == 'Y')
{
MyFile.open("test.txt");
while ( getline (MyFile, line) ) {
cout << line << '\n';
}
MyFile.close();
}
return 0;
}
+ 10
This is actually covered in our C++ course.
You include the <fstream> header to deal with files.
Create an instance of ifstream object. Read the file using the ifstream .open() method and file streams.
//assuming file line < 10
string data[10];
int counter = 0;
ifstream obj;
obj.open("yourtextfile.txt");
while (!obj.eof()) // while not end of file
{
getline(obj, data[counter]);
counter++;
}
// reads every line of text into your string array.
If you have any problems, you can post your code here for inspection.
+ 9
i would have to go through the tutorial again to find it. can you copy it into codeplayground for us?
+ 9
Hatsy = perfect as usual đ here is how one would write the file and to show that it works as presented here.
https://code.sololearn.com/cvx1oY29PV6A/?ref=app
+ 8
@Jordan You are also part of the community, so it's our (as in the possession of the entire community) course! :D
(Ofc, nobody gets paid for reporting bugs...)
+ 8
Replace input char variable with a string variable.
+ 6
+1 Hatsy. Also make sure that the text file contents are in the order the code expects them to be in.
best bet is to post the code as Hatsy recommended
+ 3
@Hatsy, you said "our C++ course". Do you work for solo learn? Who else works for solo learn? Or am I just misunderstanding?
+ 2
I am trying to make a c++ program that takes input and, if a certain input is entered, prints the contents of a text file. If statements aren't working
+ 1
I tried to use some of the example code in the tutorial, but the compiler on the computer never recognizes the "Myfile" object.
+ 1
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string line;
ifstream MyFile("test.txt");
while ( getline (MyFile, line) ) {
cout << line << '\n';
}
MyFile.close();
}
+ 1
Interesting.......but what if instead of a Y/N input, it is a whole word? How would you make that work with an if statement?