2

Trying to count the number of similar items in the text file after writing the text but i am getting an No operator << matches these operands operand type are std::ofstream >> std::string . Code works but when adding the while loop is where i get the error textfile >> item. Does it have anything to do with ofstream of the textfile?

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include<string>
using namespace std;

int main()
{

    string accord[6];

    ofstream textfile;
    textfile.open("C:\\temp\\1.txt");

    cout << "Enter a 6 cylinder car : " << endl;

    for (int x = 0; x < 6; x++) {
        getline(cin, accord[x]);
    }
    for (int x = 0; x < 6; x++) {

        textfile << accord[x] << endl;
    }
    int count = 0;
    string item;
    while (!textfile.eof()) {
        textfile >> item;
        if (item == "6") {
            count++;
        }
    }

    cout << count << "found!" << endl;



    textfile.close();
    return 0;
}
jmike
  • 443
  • 5
  • 13
  • 3
    `ofstream` means output file stream. You can't read and write at the same time. Use `ifstream` for read – Stefan Nov 26 '16 at 16:12
  • (https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Biffen Nov 26 '16 at 16:34

2 Answers2

2

Maybe because, as the error suggests, the class std::ofstream does not have that operator.

Ofstream: Output stream class to operate on files.

As you can imagine by yourself, an output stream is an object designed to write on (output). So you're not allowed input operation.

std::fstream is a both output and input stream for file. It supports operator<< operator>>.

BiagioF
  • 8,545
  • 2
  • 21
  • 45
2

Variable textfile is declared as having type std::ofstream

ofstream textfile;

There is no operator >> defined for objects of this type,

You should at first close the file and use an object of type std::ifstream with this file to read data from it.

Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268