0

so I have a file for C++ that I am reading in. It has 3 ints 4 4 16 looks like that. I'm curious as to how I go about getting this all read into 3 variables that I have cars carCapacity people

I have set up two different ways of trying to get them but neither are working. I just get an infinite loop

fin >> cars >> carCapacity >> people; Is one way that I'm trying to store the input. another was:

fin >> cars;

fin >> carCapacity

fin >> people

I'm using an ifstream to get the file, I check to make sure that there is a file and then I use while(!fin.eof()) to loop the entire txt file. Any help would be greatly appreciated. Thanks in advance!

kevorski
  • 816
  • 1
  • 11
  • 29
  • See [while feof file is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) – Chris Dodd Jun 28 '14 at 03:37

1 Answers1

2

The easiest way is to use "freeopen"

file: a.txt
1 2 3

#include <iostream>
#include <stdio.h>
using namespace std;

int main(){
   freeopen("a.txt", "r", stdin);
   int a, b, c;
   std::cin >> a >> b >> c;
   std::cout << a << b << c;
}

P/s: I don't test

  • Thanks! This is working for me. Now I just need to get out of the file loop – kevorski Jun 28 '14 at 03:40
  • How do you justify not using the standard `` ? What is freeopen ? Is it freopen ? How is reopening a stream relevant here ? – quantdev Jun 28 '14 at 03:48
  • When you use freeopen the input / output stream will be streaming a file, replacing the console stream. But this is for those using small files, even large files, I still suggest using ifstream in C + + or can be used in C FILE pointer to get the best rate. p / s: I'm a Vietnam so bad english: ( – Minh Do Van Jun 28 '14 at 03:53
  • if you want to write file can use: freeopen("b.txt", "w", stdout); – Minh Do Van Jun 28 '14 at 04:47