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;

It should be

readfile >> sample;

since you are getting input, not outputting.

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");
}

Thanks for the help I'll check it out

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.