Skip to main content

Section 11.8 Getline

Let’s try the same logic on a list of names:
Data: Names.txt
John Doe Jr.
Maria Cruz
Alice Johnson
Robert Brown
Emily K. Davis
Listing 11.8.1.
Notice that when we read into strings, whitespace still breaks up the tokens. Thus we do not get entire names, we get John, Doe, Jr.,...
To handle this better, we can use the getline function to read an entire line of text into a string variable. The getline function is part of iostream and takes two parameters: the stream and the string variable to read into. Here is an example:
Listing 11.8.2.

Note 11.8.1.

You can use getline to read an entire line from any stream, including cin. To use it on cin you would do something like getline(cin, stringVariable).
Just because a file has lines does not mean you need to use getline to read them. If every line has the same number of pieces of data and those pieces are separated by whitespace, it is likely easier to read in each part directly. For example, consider this data:
Data: Cars.txt
Honda Acura 2005
Toyota Camry 2010
Ford Focus 2015
We want to read in each line and have the make, model and year stored in separate variables. We could write an algorithm like:
while not at end of file
  read a line of the file into Line
  find the first space
  set Make to the part of Line before the space
  remove the part of Line before the space
  find the next space
  set Model to the part of Line before the space
  remove the part of Line before the space
  turn the rest of Line into an integer and
  set Year to that integer
But it would be much easier to read it the date directly into variables like this:
Listing 11.8.3.
This way, we don’t have to worry about finding spaces because >> automatically does that! We also don’t have to worry about converting the string "2005" into the integer 2005 before trying to do math with it. We do not even have to worry about where lines end! >> automatically skips over any newlines in the same way it skips over spaces.

Warning 11.8.2.

Mixing getline and >> can cause confusing issues. >> will read the last thing on a line and leave the newline there to be read (or skipped) by the next input instruction. If getline is used next, it will read that newline as an empty line.
Try to stick to one method or the other when reading a file. Either read each line and then chop it up manually, or use >> to get one token at a time.

Checkpoint 11.8.1.

You are given a file but it appears that someone’s capslock key was stuck because everything is in uppercase.
Build a definition for the function upperToLower first. Below that, build a program that takes the input from the file β€œUPPER.txt” and converts all the text to lower case.
Note that upperToLower intentionally uses pass by value to work with a copy of upper that it can freely modify.
You have attempted of activities on this page.