This code is meant to output Hello World. but it outputs 0x22fed8

前端 未结 4 2006
抹茶落季
抹茶落季 2020-12-08 11:59

I\'m learning File Handling in C++, but there is a problem here. I am trying to read a file. This code is meant to output Hello World. but it outputs 0x22fed8.



        
4条回答
  •  一向
    一向 (楼主)
    2020-12-08 12:05

    Lets examine the line

    cout << file;
    

    The reason this outputs a number is because deep under the hood fstream is a file pointer. By passing file to cout you're essentially asking for a cout of an fstream. This will default to the value of the underlying handle for the file.

    If you want to output the contents of the file, you'll need to read it in and output it line by line.

    fstream file;
    file.open("test.txt",ios::in|ios::out);
    file << "Hello World";
    file.seekg (0, ios::beg);
    while ( !file.eof() ) {
      string temp;
      file >> temp;
      cout << temp << std::eol;
    }
    
    file.close();
    

提交回复
热议问题