当前位置: 动力学知识库 > 问答 > 编程问答 >

error: printing txt file in c++ only print "0"

问题描述:

I am just trying to print this simple txt file. It opens correctly because it is successful per the code, but I am only get "0" when there is certainly more data in there.

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

网友答案:
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

No, that should not print the file. data is a file stream. There is no overloaded operator to insert a file stream into an output stream.

Perhas you intended to stream the contents instead:

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

rdbuf returns the associated stream buffer of the file stream, and there is an operator overload to insert a stream buffer into an output stream. The behaviour of the operator is to extract from the buffer until end of file is reached.


The reason why inserting a stream into a stream can compile at all is because prior to C++11, streams were implicitly convertible to a type that can be inserted into a stream.

分享给朋友:
您可能感兴趣的文章:
随机阅读: