I need to write a program for my intro class that counts the characters in book i must be able to enter at least 3 books. I can get 1 but when it get to the second it cannot open..help!

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream in_stream;
    ofstream out_stream;
    
    int bookcnt=1;
    int books;
    int asciichar [223];
    char letter;
    char letters [100];
    int cnt;
    int value;
    int lettercnt;
    char book[50];
    
  
    for (cnt=0;cnt<=223;cnt++)
    {
        asciichar[cnt]=0;
    }
    
    cout<<"How many books would you like to input?";
    cin>>books;
    
    
    while (bookcnt<=books)
    
    {
    
    cout<<"Enter file name of book "<<bookcnt<<":";
    cin>>book;
    
    in_stream.open(book);
    
    if (in_stream.fail())
    {
                         cout<<book<< " file could not be opened.\n";
                         exit (1);
    }
    
  

    while(in_stream)
    {
                      in_stream>>letter;
                      value=letter;
                      asciichar[value]++;
    }      
        
    bookcnt++;
    }

Recommended Answers

All 2 Replies

line 11: initialize the variable to be 0, not 1. All arrays start counting at 0.

line 13: you can initialize that array to be all 0s when it is declared, elmininating the need for the loop on lines 22-25. int asciichar [223] = {0}; line 31: A for loop might work better there for(bookcnt = 0;bookcnt < books; ++bookcnt) If you want to leave the loop as a while loop then change <= to just <.


delete line 51 and use letter on line 52 instead of value. It is perfectly ok to use char data type to index into arrays because char is just a one-byte integer.

The reason you can't open the second book is because in_stream is still open for the first bok. call in_stream.close() then clear the eof error by calling in_stream.clear()

aaaaaahhh thank you... i guess i have been looking at it so long i missed that... i really appreciate it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.