Reading Formatted Input in C++
This following file has a general format (or protocol!). The text is easy because it can only be interpreted in one way — as text. Sooner or later, you may be reading a file that has this kind of information in it:
Hello there my favorite number is 13. When I go to the store I buy 52 items each week, except on dates that start with 2, in which case I buy 53 items. Hello there my favorite number is 18. When I go to the store I buy 72 items each week, except on dates that start with 1, in which case I buy 73 items. Hello there my favorite number is 10. When I go to the store I buy 40 items each week, except on dates that start with 2, in which case I buy 41 items.
However, the numbers could be interpreted as text (the characters 1 and 3 for example) or as a value (the number 13). How can you read in the numbers? One way is to read strings for each of the words and skip them. Here’s a sample piece of code that reads up to the first number, the favorite number:
ifstream infile("words.txt"); string skip; for (int i=0; i<6; i++) infile >> skip; int favorite; infile >> favorite;
This code reads in six strings and just ignores them. You can see how you do this through a loop that counts from 0 up to but not including 6. (Ah, you gotta love computers. Most people would just count 1 to 6.)
Then, after you read the six strings that you just ignored, you finally read the favorite number as a number. Notice that the individual words use a variable of type string and the numeric value uses a variable of type int. You can then repeat the same process to get the remaining numbers.