0

I am trying to read all the characters in a file into an array. Assuming all variables are declared, why are all the characters not being read into my array. When I output some of the characters in the "storeCharacters[]" array, garbage is being returned. Please help.

This is my function:

void countChars(ifstream& input, char storeCharacters[])
{
int i = 0;
    while( !input.eof() )
    {
        input.get(storeCharacters[i]);
        i++;
    }
}
thomann061
  • 629
  • 3
  • 11

3 Answers3

2

After the while loop try adding storeCharacters[i] = '\0' to null terminate the string.

Kara
  • 6,115
  • 16
  • 50
  • 57
0

The easy fix to your problem if you know the maximum size of your file, then just set your array to have that size and initialize it with \0.

let's say the maximum characters count in your file is 10000.

#define DEFAULT_SIZE 10000
char  storeCharacters[DEFAULT_SIZE];
memset (storeCharacters,'\0',DEFAULT_SIZE) ;

The below post should be the correct way to read a file using a buffer it has memory allocation and all what you need to know :

Correct way to read a text file into a buffer in C?

Community
  • 1
  • 1
Mehdi Karamosly
  • 5,388
  • 2
  • 32
  • 50
0
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>


using namespace std;


void getFileName(ifstream& input, ofstream& output)  //gets filename
{
string fileName;

cout << "Enter the file name: ";
cin >> fileName;
input.open(fileName.c_str());   
if( !input )
    {
        cout << "Incorrect File Path" << endl;
        exit (0);
    }
output.open("c:\\users\\jacob\\desktop\\thomannProj3Results.txt");
}

void countWords(ifstream& input)  //counts words
{
bool notTrue = false;
string words;
int i = 0;

while( notTrue == false )
{
    if( input >> words )
    {
        i++;
    }
    else if( !(input >> words) )
        notTrue = true;
}
cout << "There are " << i << " words in the file." << endl;
}

void countChars(ifstream& input, char storeCharacters[], ofstream& output)  // counts characters
{
int i = 0;

        while( input.good() && !input.eof() )
        {
                input.get(storeCharacters[i]);
                i++;
        }
        output << storeCharacters[0];
}

void sortChars()  //sorts characters
{
}

void printCount()  //prints characters
{
}

int main()
{

ifstream input;
ofstream output;

char storeCharacters[1000] = {0};

getFileName(input, output);
countWords(input);
countChars(input, storeCharacters, output);

return 0;
}
thomann061
  • 629
  • 3
  • 11
  • im sure its something simple.... why can't I store characters from the file into the storeCharacters[] array under the countChars function? – thomann061 Apr 26 '13 at 00:17