Read from a .txt file

Mar 4, 2009 at 5:48pm
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
Mar 4, 2009 at 6:19pm
What do you mean? How is "reading from a .txt file" different from "showing the .txt file on screen"?
Mar 4, 2009 at 6:19pm
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;
}

Mar 4, 2009 at 6:30pm
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
Mar 4, 2009 at 7:52pm
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 Mar 4, 2009 at 7:54pm
Mar 4, 2009 at 7:57pm
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??
Mar 11, 2009 at 6:00pm
Could you explain more?
Mar 11, 2009 at 6:08pm
You can use cin.get(infile, character) to look at each individual character.
Mar 11, 2009 at 8:40pm
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.