Home >Backend Development >C++ >How to Read Numerical Data from a Text File in C ?

How to Read Numerical Data from a Text File in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-16 02:27:02476browse

How to Read Numerical Data from a Text File in C  ?

Reading Numerical Data from a Text File in C

Problem:

Consider a text file containing numerical data, such as:

45.78   67.90   87
34.89   346     0.98

How can we read this file in C and assign each number to a variable?

Solution:

Case 1: Reading a Limited Number of Values

If the number of values in the file is known, we can chain the >> operator to read values sequentially:

int main() {
  float a, b, c, d, e, f;
  ifstream myfile("data.txt");
  myfile >> a >> b >> c >> d >> e >> f;
  cout << a << "\t" << b << "\t" << c << "\t" << d << "\t" << e << "\t" << f << "\n";
  myfile.close();
  return 0;
}

Case 2: Reading an Unknown Number of Values

If the number of values is unknown, we can use a loop:

int main() {
  float a;
  ifstream myfile("data.txt");
  while (myfile >> a) {
    cout << a << " ";
  }
  myfile.close();
  return 0;
}

Case 3: Skipping Values

To skip a certain number of values in the file, use the following technique:

int skipped = 1233;
for (int i = 0; i < skipped; i++) {
  float tmp;
  myfile >> tmp;
}
myfile >> value;

This code skips the first 1233 values and reads the 1234th value into the value variable.

The above is the detailed content of How to Read Numerical Data from a Text File in C ?. 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