错误:在c ++中打印txt文件只打印“0”

时间:2017-01-24 23:24:41

标签: c++

我只是想打印这个简单的txt文件。它正确打开,因为它对于代码是成功的,但是当那里肯定有更多数据时我只得到“0”。

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main(){

struct item{
   string item;
   string type;
   int price;
   };


ifstream data("messageBoard.txt");
data.open("messageBoard.txt");

if (data.is_open()){
    cout<<"success"<<endl;
    }

cout<<data<<endl; //shouldn't think just print the entire file? It 
//is only printing 0, and I am also getting "success" printed as well

 while(getline(data, word, '\r')){
    cout<<"here"<<endl;

        stringstream ss;
        int wordindex=0;
        if(lineindex>0){
        ss<<word;

1 个答案:

答案 0 :(得分:1)

cout<<data<<endl; //shouldn't think just print the entire file? It 
//is only printing 0, and I am also getting "success" printed as well

不,不应该打印文件。 data是一个文件流。没有重载运算符将文件流插入到输出流中。

Perhas你打算改为流式传输内容:

cout<<data.rdbuf()<<endl;

rdbuf返回文件流的关联流缓冲区,并且有一个运算符重载将流缓冲区插入到输出流中。操作符的行为是从缓冲区中提取,直到到达文件末尾。

将流插入流中可以编译的原因是因为在C ++ 11之前,流可以隐式转换为可以插入到流中的类型。