Read from a .txt file

hey people can someone please tell me how to read from a .txt file instead of showing the .txt file on screen??

I have tried the tutorial but I get lost very easy

Thanks for all yoru help guys
What do you mean? How is "reading from a .txt file" different from "showing the .txt file on screen"?
Just an example code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
#include<fstream>

using namespace std;

int main() {

 ifstream myReadFile;
 myReadFile.open("text.txt");
 char output[100];
 if (myReadFile.is_open()) {
 while (!myReadFile.eof()) {


    myReadFile >> output;
    cout<<output;


 }
}
myReadFile.close();
return 0;
}

the problme im having is how do I read only certain bits of a file, my code is only showing one line i think

#include <stdafx.h>
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
using namespace std;


void main ()
{
{
string name;
string rent;

ifstream infile;
infile.open ("names.txt");
infile >> name >> rent;

cout << name << rent << endl;

infile.close();

}
system ("pause");
}

I think I need a getline but not sure where or how to implement it
getline is easy.
This is a modification of your code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void main ()
{
        string STRING;
	ifstream infile;
	infile.open ("names.txt");
        while(!infile.eof) // To get you all the lines.
        {
	        getline(infile,STRING); // Saves the line in STRING.
	        cout<<STRING; // Prints our STRING.
        }
	infile.close();
	system ("pause");
}
Last edited on
Excellent, is there a way to get it to look at indervidual lines? or perhaps if say "properties" was typed it would display all the prioperties in the .txt file??
Could you explain more?
You can use cin.get(infile, character) to look at each individual character.
Hello, I am using visual studio 2008 and ifstream infile and fstream infile do not work, i am using windows XP.
Topic archived. No new replies allowed.