-3

I have some code here https://github.com/Fallauthy/Projects/blob/master/cPlusPlusProjects/bazaPracownikow/bazaPracownikow/bazaPracownikow/main.cpp

And I have no idea how to show contents in my file. I mean i know how, but it doesn't show same I Have in file (in link). It show in next line. This code is responsible to load file

while (!baseFile.eof()) {
    //wczytaj zawartosc pliku do zmiennej
    std::string buffer;
    baseFile >> buffer;

    //wypisz
    loadLineFromBase += buffer;
    loadLineFromBase += " \n";
}
std::cout << loadLineFromBase << std::endl;
falauthy
  • 119
  • 1
  • 12
  • 4
    [*Why is `iostream::eof` inside a loop condition considered wrong?*](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – BoBTFish Mar 04 '16 at 22:28
  • `baseFile >> buffer` just reads one word, not a line. Use `getline()` to read a whole line. – Barmar Mar 04 '16 at 23:16

2 Answers2

0

Unless I see all your code all I can do for you is give you a sample in return, I don't know what you're trying to do but it seems in this case you're looking for this.

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

int main()
{ 

  string Display = "";
  ofstream FileOut;
  ifstream FileInput;

  FileOut.open("C:\\Example.txt");

  FileOut << "This is some example text that will be written to the file!";

  FileOut.close();

  FileInput.open("C:\\Example.txt");

  if (!FileInput)
  {
      cout << "Error File not Found: " << endl; 
      return 1; 
  }

  while (!FileInput.eof())
  {
      getline(FileInput, Display);
  } 
  FileInput.close();
  cout << Display << endl; 

  return 0;
}

Simply put if you're currently working wit ha text document

use getline()

When you use getline() it takes two arguments the first will be in this case your ifstream object, as in what you're using to open the file. The second will be the string you're using to store the contents in.

Using the method I outlined above you'll be able to read the entire file contents.

And please next time as it was said above outline your problem more in depth and if you provide us with all of your code we may better assist you!

suroh
  • 865
  • 8
  • 21
0

Your snippet of code automatically add a newline to every string read from the input file, even if originally those were words separeted by spaces. Probably you want to keep the structure of the original file, so it's better to read one line at a time and, unless you need it for some other uses, print it out in the same loop.

std::string buffer;

// read every line of baseFile till EOF
while ( std::getline(baseFile, buffer) ) {

    std::cout << buffer << '\n';
}
Bob__
  • 9,461
  • 3
  • 22
  • 31