Suzan Cioc
Suzan Cioc

Reputation: 30097

Read multiple values from file with fstream?

Can I read multiple values from tab separated text file with

double value1, value2, value3;
ifstream in;
fin.open ("myfile.dat", ifstream::in);
fin >> value1 >> value2 >> value3;

I get zeros in all values.

Upvotes: 0

Views: 8046

Answers (2)

Alex Brooks
Alex Brooks

Reputation: 1151

This worked for me:

main.cpp:

#include <fstream>
#include <iostream>
int main() {
  double value1, value2, value3;
  std::ifstream fin;
  fin.open ("myfile.dat", std::ifstream::in);
  if (fin.good()) {
    fin >> value1 >> value2 >> value3;
    printf("%f, %f, %f\n", value1, value2, value3);
  }
}

myfile.dat:

3.4893289   1.328923    3.432901

Output:

3.4893289, 1.328923, 3.432901

I hope this helps.

Upvotes: 1

Rontogiannis Aristofanis
Rontogiannis Aristofanis

Reputation: 9063

Ok, in your code there are three important mistakes:

  • fin was not declared in this scope (you probably need to change the in at the second line to fin)
  • ofstream::in does not exist, you probably mean fstream::in
  • you should also make sure that your input file exist. This can be done with fin.good()

Upvotes: 2

Related Questions