473,856 Members | 1,704 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getline questions

Consider the following snippet of code to read lines from a text file:

ifstream file_stream( "some_file.txt" );
string read_line;
while( file_stream)
{
getline( file_stream, read_line);
}

I've tried this on two text files, one whose last line concluded with a
newline character (F1) and one whose last line did not conclude with a
newline character (F2). Then I look at the file_stream.eof () and (bool)
file_stream at various points in the reading process.

For F1 (final newline), I observe:
a. After reading the last line of text, eof() is false, and file_stream
is true.
b. After one more getline, eof() is true, file_stream is false, and
read_line is empty.

For F2 (no final newline), I observe:
a. After reading the last line of text, eof() is true, and file_stream
is true.
b. After one more getline, eof() is true, file_stream is false, and
read_line is the same as it was in the previous call (i.e., the last
line of text of the file).

So now I'm trying to make sense of all this and I have a couple questions:

1. Comparing F1.b. to F2.a., why is file_stream false in the first case
and true in the second case? We've hit the EOF in both cases-- is it
because in the latter we read some characters first?

2. Comparing F1.b. to F2.b., why is read_line empty in the first case
and unchanged from the previous value in the second case?

Thanks for your help,
Mark
Sep 27 '06 #1
2 6270
Bob
On Wed, 27 Sep 2006 23:14:46 GMT, Mark P
<us****@fall200 5REMOVE.fastmai lCAPS.fmwrote:
>Consider the following snippet of code to read lines from a text file:

ifstream file_stream( "some_file.txt" );
string read_line;
while( file_stream)
{
getline( file_stream, read_line);
}

I've tried this on two text files, one whose last line concluded with a
newline character (F1) and one whose last line did not conclude with a
newline character (F2). Then I look at the file_stream.eof () and (bool)
file_stream at various points in the reading process.

For F1 (final newline), I observe:
a. After reading the last line of text, eof() is false, and file_stream
is true.
b. After one more getline, eof() is true, file_stream is false, and
read_line is empty.

For F2 (no final newline), I observe:
a. After reading the last line of text, eof() is true, and file_stream
is true.
b. After one more getline, eof() is true, file_stream is false, and
read_line is the same as it was in the previous call (i.e., the last
line of text of the file).

So now I'm trying to make sense of all this and I have a couple questions:

1. Comparing F1.b. to F2.a., why is file_stream false in the first case
and true in the second case? We've hit the EOF in both cases-- is it
because in the latter we read some characters first?
If the function extracts no characters, it calls
is.setstate(ios _base::failbit) which may throw ios_base::failu re.

In case F2.a, the read has resulted in extraction of characters. So
the file stream is still true or good.

In F1.b, no characters are extracted. The read has failed, so the
stream is set to fail or false.
>2. Comparing F1.b. to F2.b., why is read_line empty in the first case
and unchanged from the previous value in the second case?
In F1.b a sentry object is created because the file stream is still
true. Since the sentry object is true, it calls string::erase on the
passed string. So the string is erased.

In F2.a, the sentry object is false because the file stream is false.
So the passed string is not erased. It continues to contain the same
string as the previous call.

The sentry object performs some preliminary and cleanup work for the
stream.

Best wishes,

Bob
Sep 28 '06 #2
Mark P schrieb:
Consider the following snippet of code to read lines from a text file:

ifstream file_stream( "some_file.txt" );
string read_line;
while( file_stream)
{
getline( file_stream, read_line);
}

I've tried this on two text files, one whose last line concluded with a
newline character (F1) and one whose last line did not conclude with a
newline character (F2). Then I look at the file_stream.eof () and (bool)
file_stream at various points in the reading process.

For F1 (final newline), I observe:
a. After reading the last line of text, eof() is false, and file_stream
is true.
b. After one more getline, eof() is true, file_stream is false, and
read_line is empty.

For F2 (no final newline), I observe:
a. After reading the last line of text, eof() is true, and file_stream
is true.
b. After one more getline, eof() is true, file_stream is false, and
read_line is the same as it was in the previous call (i.e., the last
line of text of the file).

So now I'm trying to make sense of all this and I have a couple questions:

1. Comparing F1.b. to F2.a., why is file_stream false in the first case
and true in the second case? We've hit the EOF in both cases-- is it
because in the latter we read some characters first?

2. Comparing F1.b. to F2.b., why is read_line empty in the first case
and unchanged from the previous value in the second case?
Your "why?" has several aspects. There are technical reasons for the
behaviur you observed buried within the libraries. At the other hand
there are intended usages:

Always use 'file_stream' (e.g. the boolean value of the file-descriptor)
to check if data was retreived or if (otherwise) "something went wrong".
_If_ "something went wrong" (e.g. file_stream is false) the contents of
'read_line' has no real meaning: nothing has been read. To avoid
uninitialized variables the library returns an empty string in
'read_line' or what ever.

_After_ "something went wrong" (e.g. file_stream is false) you check for
EOF. As 'getline' returns the stream itsself the _idiom_ for the whole
loop is:

while( getline(file_st ream, read_line) ) {
<Work on read_line>
}
if( !file_stream.eo f() ) {
<Do further research on cause of error and ...>
<... possibly throw an exception>
}
// No 'else' if you threw an exception
<Go on>

You simply don't 'file_stream.eo f()' before '(! file_stream)' and you
don't access 'read_line' after.

kf
Sep 28 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3563
by: Vikram | last post by:
Hi, I don't remember if it happened previously, but nowadays I'm having problem with using cin.getline function and cin>> function simultaneously. I have Visual Studio 6. If I use cin.getline function at first and then I use the cin>> function then the next time cin.getline function does not work.
5
7754
by: vknid | last post by:
Hello, I have a question. Its probably a very newbish question so please be nice hehe. =D I have been reading through C++ Programming Fundamentals, and have come a crossed an example program that shows how to use the 'getline' function. It said: "The getline function allows you to specify how many bytes you will get from the users input. Each character the user's types takes up one byte. So if, in the getline function, you specify...
1
2152
by: ma740988 | last post by:
Consider: ifstrem MyFile("extractMe.txt"); string Str; getline(MyFile, Str); getline above extracts the contents of MyFile and place into the string object. Deduced using FROM/TO logic I could state getline's first parameter supports "FROM". The second parameter supports "TO". // later
10
5621
by: Skywise | last post by:
I keep getting the following error upon compiling: c:\c++ files\programs\stellardebug\unitcode.h(677) : error C2664: 'class istream &__thiscall istream::getline(char *,int,char)' : cannot convert parameter 1 from 'const char *' to 'char *' Conversion loses qualifiers I have a data file called Standard.udf The Data File (not the problem): The data in the file is in text format, and was created using a function in this program with...
14
3894
by: KL | last post by:
I am so lost. I am in a college course for C++, and first off let me state I am not asking for anyone to do my assignment, just clarification on what I seem to not be able to comprehend. I have a ..txt file that I want to read into a multi-dimensional string array. Each line of the file needs to be read into the array. OK..sounds easy enough, but I can't get the getline(file_name array_name) to work. So...I am thinking it is definitely...
18
8269
by: Amadeus W. M. | last post by:
I'm trying to read a whole file as a single string, using the getline() function, as in the example below. I can't tell what I'm doing wrong. Tried g++ 3.2, 3.4 and 4.0. Thanks! #include <iostream> #include <fstream> #include <cstdlib> #include <string>
2
3471
by: jalkadir | last post by:
I am trying to get character string from the user, to do that I use getline(char_type*, streamsize), but I get a segmentation fault??!! Can anyone give me a hand, what am I doing wrong? --snip char* cstr; std::cout << "House/Appartment # "; std::cin.getline(cstr, CHAR_MAX); //<<==seg fault
5
3653
by: allspamgoeshere3 | last post by:
Hi! I'm having trouble reading text lines from a file describing the levels for a simple game I'm creating. Inside the function that reads the content of the file there is a loop that basically looks like this ifstream file("levels\\level1.txt"); string line; getline(file, line);
33
25237
by: Chen shuSheng | last post by:
I have a code: --------------------------- #include <iostream.h> #include <stdlib.h> int main() { int max=15; char line; getline(line,max); system("PAUSE");
0
9908
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9760
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11052
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10695
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10777
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10379
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7930
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5759
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4573
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.