TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: FRANK MASINGILL
from: DANNY SPRINGER
date: 1997-05-27 23:02:00
subject: getline?

Hi Frank,
In a message of  to All (), you wrote:
 FM>     What is wrong with my code below:
 FM> Program to send text to a file:
 FM> #include 
 FM> void main()
 FM> {
 FM>     ofstream OutFile("MYTEST.DAT");
 FM>     OutFile << "This is line 1.\n";
 FM>     OutFile << "This is line 2.\n";
 FM> }
This code will do what you expect it does. You don't close the OutFile, it is 
better to end the program with OutFile.close();
 FM> Program to READ text from the file:
 FM> #include 
 FM> void main()
 FM> {
 FM>     const int MAX = 80;
 FM>     char buffer[MAX];
 FM>     ifstream InFile("MYTEST.DAT");
 FM>     while (InFile)
 FM>     {
 FM>         InFile.getline(buffer, MAX);
 FM>         cout << buffer;
 FM>     }
 FM> }
 FM>     Instead of the expected result of the second file reading in the two
 FM> lines as separate lines it is being read in as merged into one line.  
What
 FM> am I doing wrong?
You have to know what getline(char*, int, char) does, it reads "int" 
characters until the delimiter "char" in the "char*". After that it extracts 
the delimiter, but that one is not being stored in the "char*". So when you 
want to output the delimiter, you have to add it to the cout (cout << buffer 
<< endl;)
You can play a little bit with it when you change the '\n' with a more 
visible character:
OutFile << "This is line1.@";
OutFile << "This is line2.@";
While reading you change your lines:
InFile.getline(buffer, MAX, '@');
and when you output your buffer, you see the text without the '@'. So if you 
want to see it again, add    << "@";   to the cout line.
Regards,
Danny Springer.
(dsp@bitbike.com)
---
---------------
* Origin: Punt 12 uit Den Haag [NL] Point of AINEX (2:282/123.12@fidonet)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.