Question

I've set this up so the code will read from the file and reset a variable (count) to 0 when the program reads in a new line or line break via the if(ch == '\n') statement. However it doesn't see this no matter where I put it.

So My question is:

What is the proper way to reset a variable when a program reads in a new line?

(Just for reference the data file I'm working with is very simple, it looks like this:

TIGER

DOG

RACCOON

ZEBRA

AARDVARK

HIPPOPOTAMUS

CAT

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin;
ofstream fout;

void rectangle(char ch, int alphacount,int count)
{
for ( int height = 0; height < count; ++height )
{
  for ( int width = 0; width < alphacount; ++width )
  {
     fout << ch;
     cout << ch;
  }
  fout << endl;
  cout << endl;
 }
}

int main(void)
{
fin.open("animals.dat");
fout.open("out.dat");
int count=0, alphacount=0;
char ch, x='A';
while(!fin.eof())
{
int alphacount = 0;
count++;
char ch;
fin.get(ch);
if ( isalpha(ch) )
{
  if ( ch > 'Z' )
  {
     // It's a lower case letter.
     alphacount = ch - 'a' + 1;
  }
  else
  {
     // It's an upper case letter.
     alphacount = ch - 'A' + 1;
  }
if(ch == '\n')
  {
    cout << endl;
    fout << endl;
    count = 0;
}

  rectangle(ch, alphacount, count);


 }


}

}

EDIT:

Started using fin.get(ch) instead of fin >> ch;

But no dice, it's still not picking up the line break if statement.

Was it helpful?

Solution

Use this:

fin.get(ch);

in place of the fin >> ch; line. For additional details, check out: std::basic_istream::get. To be absolutely sure the ch variable has new content, use the fail() method before any processing (e.g. reference: std::basic_ios::fail). An example:

if ( isalpha(ch) && !fin.fail())
{
.
.
.

The basic fstream reference is here: std::basic_fstream.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top