jvance
jvance

Reputation: 551

Line Breaks when reading an input file by character in C++

Ok, just to be up front, this IS homework, but it isn't due for another week, and I'm not entirely sure the final details of the assignment. Long story short, without knowing what concepts he'll introduce in class, I decided to take a crack at the assignment, but I've run into a problem. Part of what I need to do for the homework is read individual characters from an input file, and then, given the character's position within its containing word, repeat the character across the screen. The problem I'm having is, the words in the text file are single words, each on a different line in the file. Since I'm not sure we'll get to use <string> for this assignment, I was wondering if there is any way to identify the end of the line without using <string>.

Right now, I'm using a simple ifstream fin; to pull the chars out. I just can't figure out how to get it to recognize the end of one word and the beginning of another. For the sake of including code, the following is all that I've got so far. I was hoping it would display some sort of endl character, but it just prints all the words out run together style.

ifstream fin;
char charIn;

fin.open("Animals.dat");
fin >> charIn;
while(!fin.eof()){
    cout << charIn;
    fin >> charIn;
}

A few things I forgot to include originally:

I must process each character as it is input (my loop to print it out needs to run before I read in the next char and increase my counter). Also, the length of the words in 'Animals.dat' vary which keeps me from being able to just set a number of iterations. We also haven't covered fin.get() or .getline() so those are off limits as well.

Honestly, I can't imagine this is impossible, but given the restraints, if it is, I'm not too upset. I mostly thought it was a fun problem to sit on for a while.

Upvotes: 3

Views: 3493

Answers (2)

Austin Mullins
Austin Mullins

Reputation: 7427

The >> operator ignores whitespace, so you'll never get the newline character. You can use c-strings (arrays of characters) even if the <string> class is not allowed:

ifstream fin;
char animal[64];

fin.open("Animals.dat");

while(fin >> animal) {
  cout << animal << endl;
}

When reading characters from a c-string (which is what animal is above), the last character is always 0, sometimes represented '\0' or NULL. This is what you check for when iterating over characters in a word. For example:

c = animal[0];
for(int i = 1; c != 0 && i < 64; i++)
{
    // do something with c
    c = animal[i];
}

Upvotes: 0

YXHJ513
YXHJ513

Reputation: 100

Why not use an array of chars? You can try it as follow:

    #define MAX_WORD_NUM 20
    #define MAX_STR_LEN 40 //I think 40 is big enough to hold one word.
    char words[MAX_WROD_NUM][MAX_STR_LEN];

Then you can input a word to the words.

    cin >> words[i];

Upvotes: 1

Related Questions