Home > Backend Development > C++ > body text

How to Read Numeric Data from a Text File in C : What are the Different Approaches?

Mary-Kate Olsen
Release: 2024-11-21 20:20:11
Original
885 people have browsed it

How to Read Numeric Data from a Text File in C  : What are the Different Approaches?

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;
Copy after login

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
}
Copy after login

Example: Reading Numbers from a File

Consider the following text file named "data.txt":

45.78   67.90   87
34.89   346     0.98
Copy after login

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;
}
Copy after login

Output:

45.78 67.90 87.00 34.89 346.00 0.98
Copy after login

Alternative Approaches

  • Storing Data in an Array: If you know the total number of numbers, you can store them in an array.
  • Skipping Values: To skip a certain number of values, use a loop and discard those values.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template