reading strings from files character at a time

after reading a file and distributing each character, I get a period(.) where it don't belong. Can anyone tell me what I am doing wrong. Thanks. BTW the program is not complete.

#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
#include <fstream>
using namespace std;

void openInputFile(ifstream &, string str);

int main()
{
char ch;
ifstream infile;
int k = 0;
int l = 0;
int p = 0;
const int ALPHA_SIZE = 26;
const int NUM_SIZE = 10;
char alphaArr[ALPHA_SIZE];
char numArr[NUM_SIZE];
char puncArr[5];
string inFileName = "filename";
openInputFile(infile, inFileName);

infile >> ch;
while (infile)
{
if (isalpha(ch))
{
alphaArr[k++] = ch;
}
else if (isdigit(ch))
{
numArr[l++] = ch;
}
else if (ispunct(ch))
{
puncArr[p++] = ch;
}
infile >> ch;
}

infile.close();
cout << endl;

for (int j = 0; j < k; j++)
{
cout << alphaArr[j];

}

cout << endl;

for (int h = 0; h < l; h++)
{
cout << numArr[h];
}
cout << endl;

for (int g = 0; g < p; g++)
{
cout << puncArr[g];
}
return 0;
}

void openInputFile (ifstream &infile, string inFileName)
{
if (!infile)
{
cout << " Error, file does not exist!";
exit(12);
}
else
infile.open("filename");
}
Last edited on
What input file were you trying it with? I made one up and it seemed to work quite well.

You might want to increase your array sizes a bit (or use vectors). It doesn't allow for long speeches! It is possible that you simply went beyond the end of an array. For example, you have only allowed for 5 items of punctuation and there are more than that in this reply.
Last edited on
Thanks lastchance. I ended up changing the array size to 100 and that seemed to work. I had originally 26 for my alpha array because there is 26 letters in the alphabet. If I want to keep a running total and accumulate repeated letter, am I going to need to convert it or is there another way at handling that?
miglr
If a cumulative letter count is what you are going to put in the alpha array then size 26 will be fine (assuming you put lower case and upper case versions together). As written in your posted code, however, you put all characters into the arrays, so they quickly fill up and overrun, with slightly unpredictable results.

All I can advise is to watch out for overrunning array sizes. If you need them to extend then it might be worth considering some expandable container like a vector instead. It basically depends what you want to do with the array.


the reason I put all characters into arrays was to sort them... thinking about it maybe using a vector would be easier... but I'm asked to use arrays.. one for numbers size of 10 (0-9) and accumulate repeated numbers read from a file and another array for the alphabet size of 26 (a-z) to do the same as above.
Topic archived. No new replies allowed.