没有运算符匹配流的这些操作数>>串

时间:2016-11-26 16:08:49

标签: c++

在写完文本后尝试计算文本文件中类似项目的数量,但我得到No operator << matches these operands operand type are std::ofstream >> std::string。代码有效但在添加while循环时我得到了错误textfile >> item。它与文本文件的ofstream有什么关系吗?

#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;
}

2 个答案:

答案 0 :(得分:2)

可能是因为,正如错误所示,类std::ofstream没有该运算符。

  

Ofstream:输出流类以对文件进行操作。

正如您自己可以想象的那样,输出流是一个设计用于写入(输出)的对象。因此,您不允许输入操作。

std::fstream是文件的输出和输入流。它支持operator<< operator>>

答案 1 :(得分:2)

变量textfile被声明为类型std::ofstream

ofstream textfile;

此类型的对象没有定义operator >>

您应首先关闭该文件,并使用此文件类型std::ifstream的对象从中读取数据。