3Д БУМ

3Д принтеры и всё что с ними связано

Parsing Text Files

Before you can work with ASCII files, you must know how to extract the information you need, also called parsing, from the file.

C++ is pretty strict about what it datatypes. You can’t simply set an integer equal to a string containing an integer in text format and expect it to work as you thought. Rather, you must extract and convert the data using special functions. Two of the best functions for doing this are sscanf (for extracting data from strings) and fscanf (for doing the same with files). Both functions take the same parameters, with the exception of the very first parameter. The very first parameter for sscanf is a string that holds the unformatted data, whereas the first parameter of fscanf is the file pointer you want to extract the data from.

The second parameter is the most important. It holds a string called the format string. The format string tells scanf which types of variables to look for and in what order they are. An example of a format string follows, and Table 4.1 shows you how to build your own format string.

The last variables are pointers to the variables you want to store your converted values in. You need a separate pointer for each value you read in. Because the scanf functions take a variable number of argu­ments, you can read in as many values at one time as you like.

This is best tied together with a simple example. Say you have a string, called szVertex, that contains the line:

Vertex 15 — [14.12, 12.51, 33.10];

You can see that there is a string, an integer, and three floating-point values, as well as some extra stuff such as commas, brackets, and a semicolon. You want to extract the useful parts and store them in the correct datatypes so you can use them later on in your program.

The sscanf function would look like this:

sscanf(szVertex, "%s %d — [%f, %f, %f];", s, &i, &f1, &f2, &f3);

As you can see, the format string looks a lot like the original line, only with the actual values removed. The % arguments tell sscanf what kind of variable to look for at that location. Table 4.1 shows you the most common % arguments and what they stand for. The last set of param­eters lists the destination variables. s stands for a string, probably an array of characters, &i is a pointer to an integer, and &f1, &f2, and &f3 are pointers to floating-point numbers to hold the three values be­tween the square brackets. Be sure your destination variables match up with the appropriate argument in the format string (s goes with the string, i with the integer, and f1, f2, and f3 with the three floating­point values). You can do everything shown here with fscanf, only the first parameter is the file pointer rather than a source string.

Для любых предложений по сайту: [email protected]