Home > Article > Backend Development > How do I read numeric data from a text file in C ?
Read Numeric Data from a Text File in C
When working with numeric data stored in text files, it's crucial to know how to extract and assign the numbers to variables in your C program. This becomes especially important when dealing with formatted or unstructured data that may contain whitespace or multiple values in a single line.
Assigning First Number to Variable
Using ifstream to open the text file allows you to access the data stream and read the first number. However, to read subsequent numbers, you need a way to skip the white space that separates them.
Reading Multiple Numbers Using Loop
One approach to read multiple numbers is by utilizing loop statements. The following code demonstrates how to repeat the >> operator to read numbers from a text file until none remain:
#include <iostream> #include <fstream> using namespace std; int main() { std::fstream myfile("data.txt", std::ios_base::in); float a; while (myfile >> a) { printf("%f ", a); } getchar(); return 0; }
Reading Multiple Numbers Using Chained >> Operator
If the number of elements in the file is known in advance, you can use the >> operator in sequence to read multiple numbers into separate variables:
#include <iostream> #include <fstream> using namespace std; int main() { std::fstream myfile("data.txt", std::ios_base::in); float a, b, c, d, e, f; myfile >> a >> b >> c >> d >> e >> f; printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f); getchar(); return 0; }
Skipping Values in File
If you need to skip specific values in the file and read only a particular value, you can use a loop to advance the file position:
int skipped = 1233; for (int i = 0; i < skipped; i++) { float tmp; myfile >> tmp; } myfile >> value;
Alternative Approaches
Besides the aforementioned techniques, there is an array-based approach that can be used to read and store the numeric data. Additionally, you can find useful classes and solutions on platforms like GitHub to simplify this process further.
The above is the detailed content of How do I read numeric data from a text file in C ?. For more information, please follow other related articles on the PHP Chinese website!