Home

Reading Formatted Input in C++

|
Updated:  
2016-03-26 08:29:40
|
C++ For Dummies
Explore Book
Buy On Amazon

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.

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Jeff Cogswell has been an application developer and trainer for 18 years, working with clients from startups to Fortune 500 companies. He has developed courses on C++ and other technologies.