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:
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:
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:
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.
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.
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.