-1

integers.txt has the following numbers: 1 2 3 4 5 6 7 8 9 10

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  int numbers[10];
  int i;
  ofstream outf;
  outf.open("integers.txt");
  ifstream inf;
  inf.open("in.txt");
  for(int i = 0; i < numbers[i]; i++);
  {
    outf >> numbers[10];

  }
  inf << numbers[10];
  outf.close();
  inf.close();
  return 0;
}

I want the program to output the integers from integers.txt file to an array and from the array to in.txt file. I get the following error: no match for 'operator>>' in 'outf >> numbers[10]'

Vasseurth
  • 5,984
  • 12
  • 44
  • 80

2 Answers2

2

You have swapped your file stream types.

You want to read in from integers.txt, but you opened an ofstream on the file. An ofstream only lets you output to the file, not read from it, and therefore only has the << operator defined, not >>. You want to open an ifstream on integers.txt so that you can read input from the file, and probably open an ofstream on in.txt.

ifstream inf;
inf.open("integers.txt");
ofstream outf;
outf.open("in.txt")

//read in from inf (aka integers.txt)
//output to outf (aka in.txt)
Adam Evans
  • 2,013
  • 16
  • 25
1

You are not using ifstream and ofsteam correctly. ifstream is for reading and ofstream is for writing the content to the file. However there are some more issues in your code i.e.

  • Using an uninitialized array of numbers
  • Using an uninitialized variable i
  • Trying to access the array[size] (numbers[10]) it gives an error that stack around the variable 'numbers' is corrupted

Following code will do the task for you:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  int numbers[10] = {0};
  int i = 0;
  ofstream outf;
  outf.open("in.txt");

  ifstream inf;
  inf.open("integers.txt");
  while (inf >> numbers[i])
  {
    inf >> numbers[i];
    outf << " " << numbers[i];
    i++;
  }
  outf.close();
  inf.close();
  return 0;
}
Itban Saeed
  • 1,604
  • 4
  • 22
  • 33
  • 1
    My understanding is that `while (!inf.eof())` should be replaced by `while (inf >> numbers[i])`. See [why eof is wrong](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Thomas Matthews Aug 02 '15 at 16:43
  • Thanks a lot. Correction appreciated :) – Itban Saeed Aug 02 '15 at 16:48
  • Isn't while more useful when I don't know how many integers are in a file ? But anyway thanks. – ParanoidParrot Aug 02 '15 at 16:55
  • @ParanoidParrot You are right, that is why I used `while` loop but it will not work unless you use dynamic memory for storing the integers, you can use `vectors` with a `while` loop when you do not know the exact number of integers in the file. You may accept the answer if you really find it useful. – Itban Saeed Aug 02 '15 at 18:14