Arrays are a simple and efficient form of ordered storage of data. They are used in almost every computer program. In most cases, the information in them is generated during the operation of the application. But sometimes you need to enter an array, having received data from one or another source.
Necessary
- - text editor or IDE;
- - C ++ compiler.
Instructions
Step 1
Enter an array prompting the user for data. Calculate or query the number of elements to enter. Create an array of the required size. Add a loop to the desired place in the program code to iterate over all the elements. In a loop, query the data for each item, checking if the input is correct. Various means can be used to perform data input. Using the scanf and wscanf functions of the C library is the classic way. However, these functions are insecure. A buffer overflow may result in a security error. C ++ streams provide convenient and safe input, but they also have drawbacks. The simplest example of filling an array using a standard input object might look like this: int aNumbers [10]; for (int i = 0; i <10; i ++) {std:: cout
Step 2
Enter an array from a file. Use formatted input functions (fscanf, fwscanf) and stream objects (such as ifstream) to implement simple read algorithms. Track input errors with the bad, fail, good, rdstate methods when using streams. A simple example of reading data from a file might look like this: int aNumbers [10]; std:: ifstream oFileStream ("filename.txt"); if (! oFileStream.fail ()) {for (int i = 0; (i> aNumbers ;} else std:: cout
Step 3
Enter the array directly into the program code as static data. Use array literals to initialize the corresponding variables. For example, an array of int values of undefined length, which is a static member of the class, and declared as: class CMyClass {… static const int m_anMyArray; …}; Must be initialized as follows: const int CMyClass:: m_anMyArray = {10, 20, 30, 40}; Using this method, you can enter arrays of structures of any complexity into the source code of programs.