954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Input file data

I was wondering if anyone was familiar with reading data from a file into your program. I tried using the file stream the same way cout is used but it doesnt seem to work properly. Would the getline(); function work? If so, how would that be implemented?

#include <iostream>
#include <fstream>
#include <strings>
using namespace std;

int main()
{
    fstream readFile;
    readFile.open("Input.txt");
    string sample;
    readfile<<sample;
    cout<<"Here is a line: "<<sample;
    return 0;
dmanw100
Posting Whiz in Training
242 posts since Apr 2008
Reputation Points: 104
Solved Threads: 27
 

It should be

readfile >> sample;


since you are getting input, not outputting.

mahlerfive
Junior Poster in Training
77 posts since Aug 2008
Reputation Points: 33
Solved Threads: 18
 

Well.... If you want to use the getline function, here's a simple program to test that:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	int line_number = 1;
	string line;
	ifstream myfile("test.txt");

	if(myfile.is_open())
	{
		while (!myfile.eof())
		{
			getline(myfile, line);
			cout << "line " << line_number << " --> " << line << endl;
			line_number++;
		}
	}

	else
	{
		cout << "The file cannot be opened!!" << endl;
	}

	system("PAUSE");
}
raul15791
Junior Poster
102 posts since Jun 2008
Reputation Points: 37
Solved Threads: 7
 

> while (!myfile.eof())
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046476070&id=1043284351

Use
while ( getline(myfile, line) )

Try it with a small text file (say 5 lines) and note the difference.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

Thanks for the help I'll check it out

dmanw100
Posting Whiz in Training
242 posts since Apr 2008
Reputation Points: 104
Solved Threads: 27
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You