0

I have a question to ask about reading details from text files.

In my text files, I have these information:

Employee Name: XXXXXX Address: XXXXXXXXXX Phone Number: XXXXXX Employee Name: XXXXXXXX Address: XXXXXXXX Phone Number: XXXXXX 

How can I get everything there is, in the correct format, to be output-ed into the console?

My code is:

ifstream inEmpFile; inEmpFile.open("emp.txt"); string file_contents; while(inEmpFile >> file_contents) { cout << file_contents << ' '; } inEmpFile.close(); inEmpFile.clear(); 

All I get is a chunk of text, yes the content is correct, but everything is joined together as in not in the correct format. How can I do it? Thanks in advance

8
  • 1
    What is the correct format? Commented Oct 7, 2014 at 2:58
  • You should probably take a look at loading the file line by line, and then performing the formatting you look for. Commented Oct 7, 2014 at 2:59
  • The one stated above, Employee Name: XXXXX \n Address: XXXXXX. Like that. Commented Oct 7, 2014 at 2:59
  • Show both the input format and output format if you want help. Commented Oct 7, 2014 at 3:00
  • The output format is already there. above the Code, cause if I do what I did in the code, it goes like this Employee Name: XXXXX Address: XXXXXX Phone Number: XXXXX without skipping lines at each part of the detail Commented Oct 7, 2014 at 3:01

3 Answers 3

1

just read each line separately using getline() :

while (getline(inEmpFile,file_contents)) { cout << file_contents << ' '<<endl; } 
Sign up to request clarification or add additional context in comments.

Comments

0

Use getline to get the line from the file to the string. Use cout to print the string and follow it by a new line character. Do this for every string in the file in a loop.

2 Comments

Can you please show me an example? I'm still new to C++
@Yeen: May I suggest looking at all the functions that ifstream provides here? Also, looking for examples online should be plenty.
0

Using >> ignores all the spaces. Copying the entire file can be done this way:

ifstream inEmpFile; inEmpFile.open("emp.txt"); std::cout << inEmpFile.rdbuf(); // no loop needed 

This works because of a special overload of << for std::streambuf* which is returned by rdbuf().

See (2) stream buffers std::ostream::operator<<()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.