Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
C: Record structures with strings


1. C: Record structures with strings
The C programming language has special ways in which to handle strings.

In order to avoid complexity, input that is to be assigned to a string variable, say in a record structure, should be directly read into that string field in the record structure.

Here is an example program.

2. Example program
The example program reads in each line consisting of an integer multiplication factor, a distance, and units for that distance.

The data goes until a trailer value of 0.

There are at most 50 data lines.

All input, processing and output is to be separated.

3. Record structure
The input has values for an integer factor, a floating point approximation for a distance, and text for units.

The processing requires a second distance to be calculated.

Thus, the following needs to be in the record structure.


4. Array
An array with elements that are a record structure are required. There are at most 50 data lines so 50+1 array elements are required since the first list element is 1. To avoid repeating the 50 literal, a constant named MMAX1 is used. The array is called mList1 since it is a measurement list represented as an array. To keep track of the number of data elements actually used, the variable mLen1 is used.


5. Header variable
To make it easier to process the header loop, the variable factor0 is used.


6. Header loop
The standard header loop pattern is used. Note the use of variable factor0 for the possible trailer value.

Important point: In C, the scanf into a string such as units1 should be directly into the record structure.

7. Process
The processing computes the second distance, distance2 for measurements from 1 to mLen1.


8. Output
The output goes though the array and outputs the results for measurements from 1 to mLen1..


9. Final program
Here is the final program using the above code fragments.

Here is the C code.


10. Examples of input and output
Here are some examples of input and output for the above program code.

Here is an example input.

For the above example input, here is the expected output.

Here is an example input.

For the above example input, here is the expected output.


11. End of page