tags:

views:

92

answers:

3

Possible Duplicate:
Reading through file using ifstream

Hello. I'm a bit of a newbie to C++ so please be specific. I'm trying to find a way to read something from a file, put it into a string and then output it onto the screen. If you know how to do this can you give an example? Thanks.

A: 
ifstream fin ("input.txt");

char line [200];
streamsize size (200);
fin.getline(line, size);
//or you could do:
//  string str; fin >> str;
//for every space sepped string in the file
cout << line << endl;
deftonix
Using `std::string` is safer.
dreamlax
+1  A: 
ifstream infile("myfile.txt");
std::string line;

// Reads the first line from the file and stores it into 'line'
std::getline(infile, line);

infile.close();
std::cout << line;

This code will read the entire first line of the file. If you want to read the file line by line you could do something like this:

while (!infile.eof) {
  std::getline(infile, line);
  std::cout << line << "\n"; // Not sure if std::getline includes the line terminator
}

Not sure what you mean by 'need to read something', but you could use a stringstream for conversions.

Marlon