Read multiple values from file with fstream?

北城以北 提交于 2019-12-13 06:09:35

问题


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.


回答1:


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()



回答2:


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.



来源:https://stackoverflow.com/questions/17152396/read-multiple-values-from-file-with-fstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!