alexmherrmann
alexmherrmann

Reputation: 1073

ifstream get() not filling char array

I have no clue whatsoever as to what would be doing this

#include "fstream"
#include "iostream"

using namespace std;

#define out(a) cout << #a << ": " << a << '\n'

void print(string s)
{
  cout << s << '\n';
}

 int main()
{
  ifstream readt1;
  readt1.open("test1.yaml");

  while(readt1.good())
  {
    char cc[128];
    readt1.get(cc,128);
    out(cc);
  }
readt1.close();
}

that code... outputs this:

cc: version: 0.14.1
cc: 

with test.yaml being this

version: 0.14.1
name: scrumbleship
author: dirkson
description: >
  A minecraft like game that allows you
  to build your own spaceship!

I've tried so many ways to get this to work, and it simply doesn't

Upvotes: 1

Views: 2749

Answers (3)

Jesse Good
Jesse Good

Reputation: 52365

If you add a readt1.ignore(); after the get() it should work:

  while(readt1.good())
  {
    char cc[128];
    readt1.get(cc,128);
    readt1.ignore(); // <--- add this to ignore newline
    out(cc);
  }

This fixes the immediate problem, but using std::getline and std::string would be better C++. Something like:

while(std::getline(readt1, line)) {// Do stuff}

Upvotes: 2

roguequery
roguequery

Reputation: 974

Also, I would get the first line outside of the loop, and the loop should check for an EOF to ensure you get the whole file. Doesn't good() just imply that there is a file to read?

Upvotes: 0

ravi
ravi

Reputation: 3424

You should use getline() to read line through ifstream

Upvotes: 1

Related Questions