Home >Backend Development >C++ >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 : What are the Different Approaches?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 20:20:11995browse

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;

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

  • 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!

Statement:
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