How to Read Numeric Data from a Text File in C
Reading numeric data from text files is a common task in C . It involves accessing a file and extracting numbers from it.
Approach 1: Using Multiple >> Operators
This approach involves chaining the >> operator to read multiple numbers from the file. For instance, the following code reads three numbers:
float a, b, c; myfile >> a >> b >> c;
Approach 2: Using >> in a Loop
This method uses a loop to repeatedly read numbers from the file and store them in a variable. An example is:
while (myfile >> a) { // Process the value }
Example: Reading Numbers from a File
Consider the following text file named "data.txt":
45.78 67.90 87 34.89 346 0.98
The following C program reads the numbers from this file and prints them out:
#include <iostream> #include <fstream> int main() { std::fstream myfile("data.txt", std::ios_base::in); float a; while (myfile >> a) { std::cout << a << " "; } myfile.close(); return 0; }
Output:
45.78 67.90 87.00 34.89 346.00 0.98
Alternative Approaches
The above is the detailed content of How to Read Numeric Data from a Text File in C : What are the Different Approaches?. For more information, please follow other related articles on the PHP Chinese website!