1

I am trying to open a file of integers that will be passed into a struct that holds an array, but when I try to do so I get an added zero in the output, and when I added more to my program the core is just dumped, so I'm not sure what I'm doing wrong and how to fix it.

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;

struct Hand
{
  int handCards[52];
  int totalCards;
};

struct Card
{
  char rank;
  char suit;
};

void OpenFile (ifstream&, string&);
void ReadFile (ifstream&, Hand&);
void ProcessRank (Hand&, int CardRank[]);
void ProcessSuit (Hand&, int CardSuit[]);
char GetRank (int);
char GetSuit (int);
void PrintCard (Card);
Card ConvertRaw (Hand);
void PrintHand (Card, Hand);
int main()
{
  ifstream inf;
  string filename;
  Hand theHand;
  Card aCard;
  int CardRank[13];
  int CardSuit[4];

  OpenFile(inf, filename);
  ReadFile(inf, theHand);



}

void OpenFile (ifstream &inf, string &filename)
{
  cout<<"What is the name of the file?" <<endl;
  cin>>filename;

  inf.open(filename.c_str());

  if (inf.fail())
    {
      cout<<"Sorry, that file doesn't exist" <<endl;
      exit(1);
    }
  else
    cout<<"Success!" <<endl <<endl;
}

void ReadFile (ifstream &inf, Hand &theHand)
{
  theHand.totalCards=0;
  int i=0;
  while(inf.good())
    {

      inf>>theHand.handCards[i];
      theHand.totalCards++;
      cout<<theHand.handCards[i];
      i++;
    }
}

The file is 123456, but then I get 1234560> as the output, and when I add in the rest of my code comes the core dump. I'm not sure if it's a problem passing or if my variables are off somehow, but it would mean a lot if someone can help me out.

Code-Apprentice
  • 69,701
  • 17
  • 115
  • 226
Ray Romank
  • 13
  • 2

1 Answers1

3

Normally you want to check whether your attempt at reading succeeded:

while(inf>>theHand.handCards[i])
{
  theHand.totalCards++;
  cout<<theHand.handCards[i];
  i++;
}

Of course, you should also normally use std::vector instead of an array, but I guess we can leave that for another question.

Jerry Coffin
  • 437,173
  • 71
  • 570
  • 1,035
  • This solved the problem of the file reading in an extra zero, thank you. But the problem of the core being dumped within the full program still remains, I can add the rest of the code if that will help – Ray Romank Feb 09 '13 at 00:21
  • @RayRomank: You need to identify where the core dump is occurring — which line of which function. This is what debuggers are good at, and quite often the cause is obvious when you have it pointed out to you by the debugger. Sometimes, it isn't; you've then typically got a problem somewhere else where you're writing out of bounds of allocated memory, and it just so happens that the crash site is the code that triggers the dump as it tries to allocate memory. – Jonathan Leffler Feb 09 '13 at 00:26